user3275209 user3275209 - 1 year ago 63
R Question

call columns from inside a for loop in R

I basically want to be capable to call columns from inside a for loop (in reality two nested for loops), using past() and i (j..) value of the loop to access
my data frames columns wise in a flexible manner.

#for the showcase I use the standard cars example
r1 <- cars
r2 <- cars

# in case there are more data to consider I would want to add, ore remove further with out changing the rest

# here I am entering the "dimension" of what I want to compare for the showcase its only one
num_r <- 2 #total number of reactors in the experiment

for( i in 1:num_r)
# shoud create proxie variable to be processed further
assign(paste("proxi_r",i,sep="", colapse="") ,"matrix",
list(get(paste("r",i,"$speed",sep="", colapse="" )))))
# further operations of gluing and arranging data follow so they fit tests formatting requirements


which gives me:

Error in get(paste("r", i, "$speed", sep = "", colapse = "")) :
object 'r1$speed' not found

but when typ r1$speed it obviously exists??

Sofare I searched "R object dont exist inside loop", "using paste() to acces variables inside loop", "foor loops and objects"," inside loops" ....and similar...

Is there anything to circumvent get() so I don’t have to look into the topic of environments, so I can keep the flexibility of my loops so I don’t have re-edit my script every time I have a changed the experimental configuration, which is really time consuming and allows a lot of errors to sneak inside.

The size of the data have crashed excel with extensive use of excel macros, which everyone in the lab here is using, several times :) , so there is no going back to the convort zone.
I am now trying to dig into R programming with a R statics book, and a lot of googling and reading tutorials, so please forgive my naive approach, and my lousy English.
I would be very thankful for any tips, as I feel sort of stuck right now.

Answer Source

This is a common confusion. You've created an object name "r1$speed" , i.e. a complete character string. This is not the same as the object r1 subsetted by $speed .

Try using get(paste('r',i,collapse='',sep=''))$speed

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