[R] How to return multiple values in a function

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Jun 23 11:04:42 CEST 2008


Hans-Joerg Bibiko wrote:
>
> On 23 Jun 2008, at 10:23, Gundala Viswanath wrote:
>> I apologize for this newbie question. But I can't seem
>> to find in R online manual.
>>
>> 1. How can I return two values in a function?
>> 2. How can I capture the values again of this function?
>>
>> myfunc <- function (array) {
>>
>>   # do something with array
>>   # get something assign to "foo" and "bar"
>>   print(foo)
>>   print(bar)
>>
>>  # how can I return "foo" and "bar" ?
>> }
>>
>> # Is this the way to capture it?
>>
>> (nfoo,nbar) <- myfunc(some_array)
>>
>
> One way would be :
>
> myfunc <- function (array) {
>
>   # do something with array
>   # get something assign to "foo" and "bar"
>   result <- c(foo, bar)
>   return(result)
>  # how can I return "foo" and "bar" ?
> }
>
> res <- myfunc(some_array)
> res[1]
> [1] "foo.stuff"
> res[2]
> [1] "bar.stuff"
>

safer to wrap the results into a list;  if both foo and bar are vectors,
the returned result would be *one* vector rather that a collection of
two vectors. so the generic pattern would be:

<function> = function(<args>) {
    <body>
    list(<values>)
}

?return

vQ



More information about the R-help mailing list