开发者

Referencing a column vector in a data frame within a loop

开发者 https://www.devze.com 2023-01-09 02:59 出处:网络
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

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 itsel开发者_JAVA技巧f (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. assign is the opposite of get. So breaking things up into discrete steps we have:

varname<-paste("c",1,sep="")
obj<-get(varname)
x<-"$"(obj,"values")
x<-as.numeric(as.character(x))
obj<-"$<-"(obj,"values",x)
assign(varname,obj)

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:

lapply(1:2,function(i) get(paste('c',i,sep='')))


You can index also columns by integers. This is explained in the R introductory guide on the R website.


Rather than converting your factor variables to numeric, you're probably best off figuring out why they were turned into factors in the first place.

However, since no one else has given you a decent solution to your problem, here's a simple approach with sapply and lapply:

factors <- sapply(c1, is.factor)
c1[factors] <- lapply(c1[factors], function(x) as.numeric(as.character(x)))
0

精彩评论

暂无评论...
验证码 换一张
取 消