14

In Python, one can do this:

>>> a, b, c = (1, 2, 3)
>>> a
1
>>> b
2
>>> c
3

Is there a way to do it in R, as below?

> a, b, c = c(1, 2, 3)
brandizzi
  • 26,083
  • 8
  • 103
  • 158

2 Answers2

20

You can do this within a list using [<-

e <- list()

e[c('a','b','c')] <- list(1,2,3)

Or within a data.table using :=

library(data.table)
DT <- data.table()
DT[, c('a','b','c') := list(1,2,3)]

With both of these (lists), you could then use list2env to copy to the global (or some other) environment

list2env(e, envir = parent.frame())

a
## 1
b
## 2
c
## 3

But not in general usage creating objects in an environment.

mnel
  • 113,303
  • 27
  • 265
  • 254
  • Nice... wasn't aware of `list2env` - though I can see it being abused rather than used. – thelatemail Mar 02 '13 at 03:54
  • Actually, I will not use `list2env()` - it seems rather hackish and unnatural in R - but the answer is instructive and comprehensive nonetheless. Also, I learned how to use lists! Thank you! – brandizzi Mar 02 '13 at 04:02
5

maybe it looks stupid, but I would do this :

v <- list(a=0,b=0,c=0)
v[] <- c(1,2,3)
 v
$a
[1] 1

$b
[1] 2

$c
[1] 3
agstudy
  • 119,832
  • 17
  • 199
  • 261