Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-like unpacking of numeric value in R [duplicate]

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)
like image 590
brandizzi Avatar asked Mar 02 '13 03:03

brandizzi


People also ask

What is tuple unpacking in Python?

Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.

What is unpacking sequence in Python?

Sequence unpacking in python allows you to take objects in a collection and store them in variables for later use. This is particularly useful when a function or method returns a sequence of objects.

What is tuple packing and unpacking?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.


1 Answers

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.

like image 139
mnel Avatar answered Sep 30 '22 12:09

mnel