How to assign from a function with multiple outputs?

I found list2env ideal for what you're describing; the trickiest bit, for me, was working out what to give for the env parameter:

f=function(){
    list(a=1,b="my string")
}

ret=f()
list2env(ret,env=environment())
#a=ret$a;b=ret$b    #Same as previous line

print(a);print(b)   #1  and "my string"

You can only return one object in a function. But you have some other options. You could assign intermediate objects to the global environment (you need to be careful not to overwrite anything) or you could pass an environment to your function and assign objects to it.

Here's an example of the latter suggestion:

fun <- function(x, env) {
  env$x2 <- x^2
  x^3
}
set.seed(21)
x <- rnorm(10)
myEnv <- new.env()
fun(x, myEnv)
#  [1]  4.987021e-01  1.424421e-01  5.324742e+00 -2.054855e+00  1.061014e+01
#  [6]  8.125632e-02 -3.871369e+00 -8.171530e-01  2.559674e-04 -1.370917e-08
myEnv$x2
#  [1] 6.288699e-01 2.727464e-01 3.049292e+00 1.616296e+00 4.828521e+00
#  [6] 1.876023e-01 2.465527e+00 8.740486e-01 4.031405e-03 5.728058e-06

Tags:

R