Skip to content

Calling objects in a loop

4 messages · Brendan Morse, Duncan Murdoch, Dimitri Liakhovitski +1 more

#
On 4/20/2009 2:35 PM, Brendan Morse wrote:
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
#
Brendan,

I think you should create objects outside of the "for" loop. You can't
create objects instide the loop. You can try this:

metalist1<-list()
for(i in 1:10) {metalist1[[i]]<-assign(paste("theta1_",i,sep=""),data.frame(scale(rnorm(250))))}
lapply(metalist1,function(x){print(dim(x))}) # Checking it out

metalist2<-list()
for(i in 1:10) {metalist2[[i]]<-assign(paste("theta1_",i,sep=""),data.frame(scale(rnorm(250))))}
lapply(metalist1,function(x){print(dim(x))}) # Checking it out

metalist3<-list()
for(i in 1:10) {metalist3[[i]]<-metalist1[[i]]+metalist2[[i]]}
lapply(metalist3,function(x){print(dim(x))}) # Checking it out

# Checking
sum(metalist1[[1]]+metalist2[[1]])
sum(metalist3[[1]])

Dimitri
On Mon, Apr 20, 2009 at 2:35 PM, Brendan Morse <morse.brendan at gmail.com> wrote: