[R] Calling objects in a loop

Duncan Murdoch murdoch at stats.uwo.ca
Mon Apr 20 20:49:10 CEST 2009


On 4/20/2009 2:35 PM, Brendan Morse wrote:
> Hi everyone, I am trying to calculate a particular variable (vector) from
> some previously defined variables in a loop but I am having trouble figuring
> out how to get the loop to recognize that it should index for the previously
> defined objects. Here is a simplified version of what I am trying to do:
> 
> for(i in 1:10){
> 
> assign(paste("theta1_",i,sep=""),data.frame(scale(rnorm(250))))
> 
> assign(paste("theta2_",i,sep=""),data.frame(scale(rnorm(250))))
>                       assign(paste("theta3_",i,sep=""),data.frame(theta1_i +
> theta2_i)
>                    }
> 
> I am having trouble with getting it to recognize that theta3_i should be
> calculated using theta1_i and theta2_i in the third line. In other words,
> theta3_1 should equal theta1_1+theta2_1 whereas theta3_2 should equal
> theta1_2+theta2_2
> 
> Any advice as to where I am losing this one?

You have no variables theta1_i and theta2_i.  You would have to 
construct the names and use get() to get the associated values.  But why 
make your life so complicated?  Why not just store everything in lists, 
indexed by i?  E.g.

theta1 <- list()
theta2 <- list()
theta3 <- list()
for (i in 1:10) {
   theta1[[i]] <- data.frame(scale(rnorm(250)))
   etc.

(You could even put everything in a single list of lists, but I don't 
think that makes it easier to read.)

Duncan Murdoch




More information about the R-help mailing list