Created
November 26, 2016 00:24
-
-
Save goldingn/1df48e7140af0358c79e0edf05872bde to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# an 'unpack' operator, to do python/MatLab-like multiple assignment from | |
# functions | |
`%=%` <- function (expr, list) { | |
if (!is.list(list)) | |
stop ('the right hand side must be a list') | |
# grab the names to assign to | |
expr <- substitute(expr) | |
names_list <- lapply(expr, as.character)[-1] | |
# drop any outputs for which the name was NULL | |
blanks <- vapply(names_list, function (x) length(x) == 0, FALSE) | |
if (any (blanks)) { | |
list <- list[which(!blanks)] | |
names_list <- names_list[which(!blanks)] | |
} | |
names <- unlist(names_list) | |
# assign the names to the list | |
names(list) <- names | |
# do list2env into parent environment | |
list2env(list, envir = parent.frame()) | |
invisible(NULL) | |
} | |
# ~~~~~~~~~~~~~~ | |
# example | |
foo <- function() list(1, 2, 3) | |
# assign the elemtns to these names | |
{a; b; c} %=% foo() | |
a | |
# [1] 1 | |
b | |
# [1] 2 | |
c | |
# [1] 3 | |
# skip (don't assign) one of the elements by using NULL instead of an object | |
{a1; NULL; c1} %=% foo() | |
a1 | |
# [1] 1 | |
c1 | |
# [1] 3 | |
# only these 5 objects were assigned | |
ls() | |
# [1] "%=%" "a" "a1" "b" "c" "c1" "foo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment