1

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

89_Simple
  • 3,393
  • 3
  • 39
  • 94
  • 2
    `mdl <- integer(30)` outside the loop (first), and `mdl[i] <- i` inside the loop. This might help http://stackoverflow.com/questions/32620557/simple-function-in-r/32620651#32620651 – Rich Scriven Oct 04 '15 at 20:23
  • thanks. But is there any way I don't have to specify `mdl<-integer(30)` beforehand. I am not sure how many mdl I will have since the data is very big. I was just wondering if there is any way I can make mdl take the name of value corresponding to i – 89_Simple Oct 04 '15 at 20:31
  • But you have a sequence of known length so it makes sense to allocate the vector of the same length as the length of the sequence in the `for()` statement. – Rich Scriven Oct 04 '15 at 20:39
  • thanks for the help. – 89_Simple Oct 04 '15 at 20:42
  • Btw, for names you could do `mdl <- NULL; for(i in 1:10) mdl[paste0("mdl", i)] <- i` – Rich Scriven Oct 04 '15 at 20:45

1 Answers1

1

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.

Alex
  • 4,925
  • 2
  • 32
  • 48