Gago-Silva Gago-Silva - 1 month ago 8
R Question

How to assign from a function with multiple outputs?

Is there a way to output e.g. 2 objects without using

list()
?

my.fun=function(vector, index)
{
a=fun.a(vector, index)
b=fun.b(vector, index)
output=list(a,b)
}


Or to output 2 lists of objects? Considering that I could also have:

c=fun.a(vector, index)
d=fun.b(vector, index)


And wanted
list(a,b)
and another
list(c,d)
for the same function.

This is just a small example for what I am looking for, my function is applied to large objects and I export them as a list, however I would like to export also an intermidiate calculation. One option would be to merge all in the same list, but I would like to know if there is another solution to this.

Answer

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"