In a loop, I am trying to get a column vector of class factor into numeric.
If there were not a loop, the code would look like
c1$values <- as.numeric(as.character(c1$values))
But how do I reference c1$values with a loop? I have tried two approaches:
get(paste('c',i,"$values", sep=""))
just does not work even outside the loop, while
get(paste('c',"1", sep=""))[[1]]
works in itself (returns the column vector), but when trying to perform the operation:
assign(get(paste("c","1", sep=""))[[1]], as.numeric(as.character(get(paste("c","1", sep=""))[[1]])))
returns an error of “invalid first argument”.
Any ideas?
Thanks,
Roberto
Internally the
$operator is a function that can be explicitly called as"$"for getting and"$<-"for setting.assignis the opposite ofget. So breaking things up into discrete steps we have:But having data (such as an index) encoded into a variable name is not good practice. It might be a better idea to turn the c1,c2 etc. into a list or a data frame and then iterate over them. The conversion can be done by something like this: