89_Simple
89_Simple

Reputation: 3805

store results of for loop in unique objects

Here is a simple loop

 for (i in seq(1,30)) {
    mdl<-i
 }

How do I get 30 mdl rather than just one mdl (which is happening because within the loop, mdli is being replaced by mdli+1 at every iteration. What I want is to have 30 mdl perhaps with names like mdl1, mdl2 ....mdl30

I tried this:

for (i in seq(1,30)) {
   mdli<-i
 }

But if I type mdl1, it says mdl1 not found whereas typing mdli gives me the value of i=5

Thank you

Upvotes: 1

Views: 135

Answers (1)

Alex
Alex

Reputation: 4995

You can specify your store variable beforhand without determine how many values it shall store. If you want for each value a seperate variable take a look at the paste function.

x<- NULL
for (i in 1:10){
x[i] <- i*2
}

*edit: The comment above is right. This way is not the most efficent one. But I still use it when computation time is not an issue.

Upvotes: 1

Related Questions