-2

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

assign(paste("contractrenewal",i, 
             "[,\"SContract Product ID from Object\"]",sep = ""), 
       as.character(paste("contractrenewal",i, 
                          "[,\"SContract Product ID from Object\"]", sep = "")))

Here, i runs from 1 to 18 and I have 18 dataframes that are as follows (contractrenewal1, contractrenewal2, ... , contractrenewal18). 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

sindri_baldur
  • 22,360
  • 2
  • 25
  • 48
  • 3
    You are going about things in a very non-R like way. `assign()` can only be used with variable names (symbols). Something like `d[i]` is **not** a variable name. The `[]` is actually a function call. We can probably suggest a better way if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. – MrFlick Feb 27 '17 at 15:55
  • 4
    [Use a list of data frames](http://stackoverflow.com/a/24376207/903061). – Gregor Thomas Feb 27 '17 at 16:05

1 Answers1

2

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).

Community
  • 1
  • 1
sindri_baldur
  • 22,360
  • 2
  • 25
  • 48