Return a list
that's likely to work, but it's even worse than my non-functional version: the destructive operation on the test's caller's environment is performed here by the callee (test), and you can get ugly surprises if you forget that test does that. i'd consider this (and the 'for (name in names(result)) assign(...)' solution) an anti-pattern. vQ
N. Lapidus wrote:
The answers that were previously given allow you to easily extract results from your returned list, but if I understand well, this list is created only because you cannot return several arguments whereas you need to keep the values of a, b, c, etc. Am I right? Another solution would be to directly "send" the values you want to keep into the environment where they are needed. The following example supposes you need to keep "a" only in the upper environment from which your function was launched, and "b" in another one (e.g. .GlobalEnv). Hope this may help. Nael
# Here is a function such as yours:
test <- function(){
+ a <- 1 + b <- 2 + return(list(a=a, b=b, c=c)) + }
result <- test()
(a <- result$a)
[1] 1
(b <- result$b)
[1] 2
rm(a, b)
# Now our variables will be automatically assigned into the chosen
environment
test2 <- function(){
+ a <- 1
+ b <- 2
+ assign("a", a, envir=parent.frame(n=1))
+ assign("b", b, envir=.GlobalEnv)
+ return(NULL)
+ }
# Suppose test2 is launched by another function
test2.launcher <- function() {
+ test2()
+ print(paste("a exists inside test2.launcher:", exists("a")))
+ print(paste("b exists inside test2.launcher:", exists("b")))
+ return (NULL)
+ }
test2.launcher()
[1] "a exists inside test2.launcher: TRUE" [1] "b exists inside test2.launcher: TRUE" NULL
exists("a")# a still exists in the upper environment
[1] FALSE
exists("b")# b does not
[1] TRUE