Multiple assignment in R? [duplicate]
Asked Answered
H

2

6

In python you can do something like this:

x,y = 1,2 

or

x,y = function_that_returns_two_elements()

I was trying to do something similar in R but found no solution. Is it possible?

Harmonize answered 11/3, 2022 at 20:5 Comment(1)
Why not just make the function's return value a list of length 2?Marotta
C
5

The zeallot package offers an unpacking operator, %<-%

library(zeallot)

z <- list(1:3, 6:9)

c(a, b) %<-% z

a
# 1 2 3

b 
# 6 7 8 9
Callender answered 11/3, 2022 at 20:38 Comment(0)
B
2

We can use multiple assignment operator (%=%) for this

library(collapse)
c("x", "y") %=% c(1,2)

-output

> x
[1] 1
> y
[1] 2

If it should be unquoted

rm(x, y) # remove the objects from the global environment
.c(x, y) %=% c(1, 2)

-output

> x
[1] 1
> y
[1] 2
Beem answered 11/3, 2022 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.