Skip to content

Instantly share code, notes, and snippets.

@kvasilopoulos
Created August 8, 2020 01:01
Show Gist options
  • Save kvasilopoulos/04863da07ac6e97cd544c0e4e159aca4 to your computer and use it in GitHub Desktop.
Save kvasilopoulos/04863da07ac6e97cd544c0e4e159aca4 to your computer and use it in GitHub Desktop.
How to assign from a function which returns more than one value?
# (https://stackoverflow.com/questions/1826519/how-to-assign-from-a-function-which-returns-more-than-one-value)
':=' <- function(lhs, rhs) {
frame <- parent.frame()
lhs <- as.list(substitute(lhs))
if (length(lhs) > 1)
lhs <- lhs[-1]
if (length(lhs) == 1) {
do.call(`=`, list(lhs[[1]], rhs), envir=frame)
return(invisible(NULL))
}
if (is.function(rhs) || is(rhs, 'formula'))
rhs <- list(rhs)
if (length(lhs) > length(rhs))
rhs <- c(rhs, rep(list(NULL), length(lhs) - length(rhs)))
for (i in 1:length(lhs))
do.call(`=`, list(lhs[[i]], rhs[[i]]), envir=frame)
return(invisible(NULL))
}
functionReturningTwoValues <- function() {
return(list(1, matrix(0, 2, 2)))
}
c(a, b) := functionReturningTwoValues()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment