Search code examples
riterable-unpacking

Python-like unpacking of numeric value in R


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)

Solution

  • 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.