Solved – Produce a list of variable name in a for loop, then assign values to them

r

I wonder if there is a simple way to produce a list of variables using a for loop, and give its value.

for(i in 1:3)
{
  noquote(paste("a",i,sep=""))=i
}

In the above code, I try to create a1, a2, a3, which assign to the values of 1, 2, 3. However, R gives an error message. Thanks for your help.

Best Answer

Your are looking for assign().

for(i in 1:3){
  assign(paste("a", i, sep = ""), i)    
}

gives

> ls()
[1] "a1"          "a2"          "a3" 

and

> a1
[1] 1
> a2
[1] 2
> a3
[1] 3

Update

I agree that using loops is (very often) bad R coding style (see discussion above). Using list2env() (thanks to @mbq for mentioning it), this is another solution to @Han Lin Shang's question:

x <- as.list(rnorm(10000))
names(x) <- paste("a", 1:length(x), sep = "")
list2env(x , envir = .GlobalEnv)