[R] Looping

Duncan Murdoch murdoch at stats.uwo.ca
Wed Oct 24 16:47:07 CEST 2007

On 10/24/2007 10:30 AM, yiferic at berkeley.edu wrote:
> Is there a way to generate variables with names like var1, var2, var3?
> Right now I've been resorting to using either a cat function to string it
> together or to pre-generate a list and having it select from list[x] as it
> loops.

Your last resort (using a list) is the preferred way to do it, but you 
can use assign(name, value) to assign the value to the character string 
stored in name.  So

for (i in 1:3) assign( paste("var", i, sep=""), i)

will do what you asked.  However, I'll say it again:  you really are 
better off using

var <- list()
for (i in 1:3) var[[i]] <- i

If your list is very long, you may want to allocate all the entries it 
it at the start, using something like

var <- vector("list", 3)


var <- as.list(1:3)

Duncan Murdoch

More information about the R-help mailing list