Skip to content

Instantly share code, notes, and snippets.

@RaphaelS1
Last active March 16, 2022 15:52
Show Gist options
  • Save RaphaelS1/be9fe23f51a3d7e79fb251e5cce4b946 to your computer and use it in GitHub Desktop.
Save RaphaelS1/be9fe23f51a3d7e79fb251e5cce4b946 to your computer and use it in GitHub Desktop.
Multiple assignment of variable values in R
`%=%` <- function(l, r) {
l <- trimws(strsplit(l, ",", TRUE)[[1]])
if (all(l == "USE.NAMES") || all(l == "*") || all(l == "?")) {
stopifnot(length(names(r)) > 0)
l <- names(r)
} else {
stopifnot(identical(length(l), length(r)))
which <- l == "?"
if (any(which)) {
stopifnot(length(names(r)) > 0)
l[which] <- names(r)[which]
}
}
invisible(Map(assign, l, r, MoreArgs = list(envir = parent.frame())))
}
@RaphaelS1
Copy link
Author

RaphaelS1 commented Feb 4, 2022

  `%=%` <- function(l, r) {
    l <- trimws(strsplit(l, ",", TRUE)[[1]])
    if (all(l == "USE.NAMES") || all(l == "*") || all(l == "?")) {
      stopifnot(length(names(r)) > 0)
      l <- names(r)
    } else {
      stopifnot(identical(length(l), length(r)))
      which <- l == "?"
      if (any(which)) {
        stopifnot(length(names(r)) > 0)
        l[which] <- names(r)[which]
      }
    }

    invisible(Map(assign, l, r, MoreArgs = list(envir = parent.frame())))
  }

  ## Use quotes around comma-separated variable names (spaces trimmed) to
##  assign multiple variables at once
"x, y" %=% range(runif(100))
x
#> [1] 0.006797081
y
#> [1] 0.9920904

# Errors
"x" %=% range(runif(100))
#> Error in "x" %=% range(runif(100)): identical(length(l), length(r)) is not TRUE

# Works with vectors and lists
"x, y" %=% c(pi, Inf)
x
#> [1] 3.141593
y
#> [1] Inf

"x, y" %=% list(1, "a")
x
#> [1] 1
y
#> [1] "a"

## Dynamic naming
# combine dynamic and set
"c,?" %=% list(a = 1, b = 2)
a
#> Error in eval(expr, envir, enclos): object 'a' not found
b
#> [1] 2
c
#> [1] 1

# all dynamic
"USE.NAMES" %=% list(e = 1, f = 2)
  e
#> [1] 1
  f
#> [1] 2

# shorter wild character
"*" %=% list(i = 1, j = 2)
  i
#> [1] 1
  j
#> [1] 2

Created on 2022-03-16 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment