For example I have 2 variables a
and b
(actually more than 2 in my real case), can I assign values for them in a way like c(a,b)<-c(0,0)
, just like the Tuple in Python? Thank you.
Asked
Active
Viewed 685 times
1

Ziyuan
- 4,215
- 6
- 48
- 77
-
@JackManey Yes I tried but didn't get through. I am asking ways of assignment with the same effect. – Ziyuan Nov 12 '12 at 18:38
-
If you want to assign them to all be the same value (i.e. 0 in your example), you can do `a = b = 0`. But there isn't an equivalent to tuple unpacking in R. – David Robinson Nov 12 '12 at 18:43
-
Please see [this question](http://stackoverflow.com/questions/7519790/assign-multiple-new-variables-in-a-single-line-in-r) – Ricardo Saporta Nov 12 '12 at 23:13
2 Answers
2
There's no built in way to do it - what you're looking for is very similar to lists
and vectors
in R
- instead of calling back a
, b
, and c
, you call back a[1]
, a[2]
, and a[3]
. If it's important for you to be able to call back this values by separate names, and to be able to assign them from the same line, you can make a simple function:
Assign <- function(Names, Values) {
for(i in 1:length(Names)){
assign(Names[i], Values[i], envir=.GlobalEnv)
}}
>A <- c("a", "b", "c", "d")
>B <- c(0,4,2,3)
>Assign(A,B)
>c
#[1] 2
I couldn't figure out a way for the apply
family to tackle this one without making it too complicated - maybe someone could help me out.

Señor O
- 17,049
- 2
- 45
- 47
-
1`Assign <- function(Names, Values) {sapply(seq_along(Names), function(i){assign(Names[i], Values[i], envir=.GlobalEnv)});invisible()}` Not too terribly complicated - just use `sapply` or `lapply` on a vector of the indices and create an anonymous function to do the actual assignment. I put the invisible in there to make it a little nicer. – Dason Nov 12 '12 at 19:01
-
Thanks - I've never tried `seq_along` before - seems like a good alternative for a task that really needs a `for` loop but is susceptible to the disadvantages that come along with loops. – Señor O Nov 12 '12 at 19:06
-
4or `mapply(assign, Names, Values, MoreArgs = list(envir = .GlobalEnv))` – flodel Nov 12 '12 at 19:21
-
1
You can use %=%
as explained in this question
(you have to copy and paste the four functions)
# Example Call; Note the use of g() AND `%=%`
# Right-hand side can be a list or vector
g(a, b, c) %=% list("hello", 123, list("apples, oranges"))
# Results:
> a
[1] "hello"
> b
[1] 123
> c
[[1]]
[1] "apples, oranges"

Community
- 1
- 1

Ricardo Saporta
- 54,400
- 17
- 144
- 178
-
Thanks for the link - looks like this question should probably be closed as a duplicate. – Dason Nov 13 '12 at 00:12