Hi,
I am moving from MATLAB, where one can easily assign a number of
output values from a function like this:
[x,y] = myfun(a,b)
Then variables x and y can be directly used in the caller workspace.
I understand that R functions return a single argument, which could be
a list. This in a way makes it possible to return multiple values with
a single function call, but accessing the list variables is a little
bit awkward.
mylist <-myfun(a,b) {
return(list(x = a, y = b))
}
x = mylist$x; y = mylist$y
I found some discussion going back to 2004. Is there anything new to
add to what was said at the time?
http://thread.gmane.org/gmane.comp.lang.r.general/21223/focus=21226
http://thread.gmane.org/gmane.comp.lang.r.general/42875/focus=42876
While at it, somewhere in the "Introduction to R", I think, I read
that use of "return" is considered a bad practice. Why is that? I
thought making clear what is returned by the function is a positive
thing...
Regards,
TL
How to assign multiple return values
2 messages · Tribo Laboy, Duncan Murdoch
On 24/03/2008 5:09 AM, Tribo Laboy wrote:
Hi,
I am moving from MATLAB, where one can easily assign a number of
output values from a function like this:
[x,y] = myfun(a,b)
Then variables x and y can be directly used in the caller workspace.
I understand that R functions return a single argument, which could be
a list. This in a way makes it possible to return multiple values with
a single function call, but accessing the list variables is a little
bit awkward.
mylist <-myfun(a,b) {
return(list(x = a, y = b))
}
x = mylist$x; y = mylist$y
I found some discussion going back to 2004. Is there anything new to
add to what was said at the time?
http://thread.gmane.org/gmane.comp.lang.r.general/21223/focus=21226
http://thread.gmane.org/gmane.comp.lang.r.general/42875/focus=42876
I don't think so.
While at it, somewhere in the "Introduction to R", I think, I read that use of "return" is considered a bad practice. Why is that? I thought making clear what is returned by the function is a positive thing...
Where did you see that? It would be good advice if it said not to hide many calls to return() deep within a long function. I'd be neutral about it if it said not to bother with return() in a very short function. In intermediate cases, I think using return() is good practice. Duncan Murdoch