Roberto
Roberto

Reputation: 2990

Referencing a column vector in a data frame within a loop

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

Upvotes: 0

Views: 6123

Answers (3)

hadley
hadley

Reputation: 103898

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

Upvotes: 0

zvrba
zvrba

Reputation: 24546

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

Upvotes: 1

Jyotirmoy Bhattacharya
Jyotirmoy Bhattacharya

Reputation: 9587

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='')))

Upvotes: 1

Related Questions