[R] How to return more than one variable from function
Vincent Goulet
vincent.goulet at act.ulaval.ca
Fri Apr 20 16:25:48 CEST 2007
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. 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))
}
>
> 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
More information about the R-help
mailing list