[R] multiple return values

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Mon Mar 20 19:49:50 CET 2006



Gavin Simpson wrote:
> On Mon, 2006-03-20 at 13:06 -0500, Sam Steingold wrote:
> 
>>I am pretty sure I saw this mentioned in
>>http://cran.r-project.org/doc/manuals/R-intro.html
>>but I cannot recall how it was called. sorry...
>>
>>how do I return (and accept) multiple return values from a function?
>>
>>e.g., in lisp (multiple-value-bind (f r) (floor 10 3) (list f r))
>>will return list (3 1).
>>
>>thanks!
>>
> 
> 
> Generally in a list, like this:
> 
> foo <- function(x)
>   {
>     dat <- runif(x)
>     m <- mean(dat)
>     ran <- range(dat)
>     retval <- list(mean = m, range = ran)
>     return(retval)
>     ## or in one step:
>     ## return(list(mean = m, range = ran))
>   }
> 
> foo(100)
> 
> bar <- foo(100)
> bar
> 
> HTH
> 
> G
> 

Note that using "return" as you have is not necessary (and some would 
say, not good style -- but I digress...).

foo <- function(x)
   {
     dat <- runif(x)
     m <- mean(dat)
     ran <- range(dat)
     list(mean = m, range = ran)
   }

foo(100)

This is mentioned in ?return.

HTH,

--sundar




More information about the R-help mailing list