Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop object names iterate [duplicate]

Tags:

r

I am working on a project where I have to do a lot of repeating and life would be a lot easier if i could address multiple objects in a for loop. To elleborate my question i have come up with a (silly) example

For instance if have done this to create my data:

for (i in 1:10)
  {
assign(paste("Season",i, sep = ""),rnorm(10,0,1))
}

So I have Season1, Season2,..,Season10. Is it possible to change the first number of the 10 objects to zero using a for loop. Semi pseudocode looks like this. But of course this does not work.

for (i in 1:10)
  {
Seasoni[1]<-0
}

Anyone with a solution?

Stefan

like image 825
UserX Avatar asked Oct 08 '13 18:10

UserX


1 Answers

The direct solution to your question would be to use get with paste

for(i in 1:10)  
{
    Object = get(paste0("Season", i))
    Object[1] = 0
    assign(paste0("Season", i), Object)
}

But don't do this.

It's a horrible use of R. As suggested in the comments, store results in lists:

Seasons = lapply(rep(10,10), rnorm) #Generate data
Seasons

Then apply functions:

Seasons = lapply(Seasons, replace, list=1, values=0)
like image 166
Señor O Avatar answered Oct 14 '22 16:10

Señor O