[R] How to return more than one variable from function

Liaw, Andy andy_liaw at merck.com
Fri Apr 20 17:23:41 CEST 2007


From: Vincent Goulet
> 
> Le Vendredi 20 Avril 2007 07:46, Julien Barnier a écrit :
> > Hi,
> >
> > > I have written a function which computes variance, sd,
> > > r^2, R^2adj etc. But i am not able to return all of
> > > them in return statement.
> >
> > You can return a vector, or a list.
> >
> > For example :
> >
> > func <- function() {
> >   ...
> >   result <- list(variance=3, sd=sqrt(3))
> >   return(result)  # you can omit this
> > }
> 
> Nitpicking and for the record: if you omit the 
> "return(result)" line, the 
> function will return nothing since it ends with an 
> assignment.

Have you actually checked?  Counterexample:

R> f <- function(x) y <- 2 * x
R> f(3)
R> (z <- f(3))
[1] 6
R> f2 <- function(x) { y <- 2 * x; y }
R> f2(3)
[1] 6


> Furthermore, 
> explicit use of return() is never needed at the end of a 
> function. The above 
> snippet is correct, but this is enough:
> 
> func <- function() {
>   ...
>   result <-list(variance=3, sd=sqrt(3))
>   result
> }
> 
> But then, why assign to a variable just to return its value? 
> Better still:
> 
> func <- function() {
>   ...
>   list(variance=3, sd=sqrt(3))
> }

Or, as has been suggested, if all values to be returned are of the same type, just use a (named) vector:

func <- function(...) {
    ...
    c(Variance=3, "R-squared"=0.999)
}

Andy
 
> 
> >
> > a <- func()
> > a$variance
> > a$sd
> >
> > HTH,
> >
> > Julien
> 
> -- 
>   Vincent Goulet, Professeur agrégé
>   École d'actuariat
>   Université Laval, Québec 
>   Vincent.Goulet at act.ulaval.ca   http://vgoulet.act.ulaval.ca
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}



More information about the R-help mailing list