0

Is there a way to assign a value to 2 variables. For example

q <- 3
q
[1] 3

But something like this

q , w <- 2  ## both q and w should hold value 2
q
[1] 3
w
[1] 3
manu p
  • 952
  • 4
  • 10

1 Answers1

0

One option is to use the zealott package, which uses the %<-% operator allowing you to assign values to q and w.

library(zeallot)

c(q, w) %<-% rep(2, 2)

q
#[1] 2
w
#[1] 2

Another option is to use purrr:

purrr::walk2(c("q", "w"), 2, assign, envir = parent.frame())

This option can use just 1 number or if you do have a vector of values, then those could be provided as well:

purrr::walk2(c("q", "w"), c(2, 3), assign, envir = parent.frame())

q
#[1] 2
w
#[1] 3

Or the simplest (as shown by @DarrenTsai) if you only have 1 number is to use base R:

q <- w <- 2
AndrewGB
  • 16,126
  • 5
  • 18
  • 49