Jamey Copeland Jamey Copeland -4 years ago 79
R Question

dynamically naming variables in R

I am trying to dynamically change the type of a variable in a loop. Right now I have the following line of code

"[,\"SContract Product ID from Object\"]",sep = ""),
"[,\"SContract Product ID from Object\"]", sep = "")))

Here, i runs from 1 to 18 and I have 18 dataframes that are as follows (
, ... ,
). I have a column in each of these dataframes names
SContract Product ID from Object
that is of type int and I want it to be of character type.

The above code executes fine, but does not achieve what I am looking for. I have looked around and haven't been able to find anything like this

Answer Source

A quick (and perhaps dirty) fix:

Follow Gregor's link and put all your data frames into a list.

(To reproduce your example I made my own list:)

cr.list <- list()
for (i in 1:18) {
  cr.list[[i]] <- data.frame("SContract Product ID from Object" = 
                               as.integer(c(123, 412))) 

Then you can loop through the list:

for (i in 1:18) {
  cr.list[[i]][, "SContract.Product.ID.from.Object"] <- 
    as.character(cr.list[[i]][, "SContract.Product.ID.from.Object"])

And now you can see that your variable is a character using str(cr.list).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download