Skip to main content
Included another solution to the OP's question
Source Link
Bernd Weiss
  • 7.3k
  • 31
  • 40

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)

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

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)
Source Link
Bernd Weiss
  • 7.3k
  • 31
  • 40

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