[R] Best way to export values from a function?

Godmar Back godmar at gmail.com
Thu Jul 9 02:57:33 CEST 2009


On Wed, Jul 8, 2009 at 8:34 PM, Jason Rupert<jasonkrupert at yahoo.com> wrote:
>
> Maybe there is a great website out there or white paper that discusses this but again my Google skills (or lack there of) let me down.

Yeah, R is difficult to search for - I've had partial success with
rseek.org, though.

>
> I would like to know the best way to export several doubles from a function, where the doubles are not an array.
>
> Here is a contrived function similar to my needs:
>
> multipleoutput<-function(x)
> {
>        squared<-x^2
>        cubed<-x^3
>        exponentioal<-exp(x)
>        factorialVal<-factorial(x)
>
> }

You can always do:

> multipleoutput <- function (x) { return (c(square = x^2, cube = x^3, exp = exp(x))) }

But then you'd have to call it like so:

> mapply(multipleoutput, c(0,1,2))
       [,1]     [,2]     [,3]
square    0 1.000000 4.000000
cube      0 1.000000 8.000000
exp       1 2.718282 7.389056

If you call it like so:

> multipleoutput(c(0,1,2))
 square1  square2  square3    cube1    cube2    cube3     exp1     exp2
0.000000 1.000000 4.000000 0.000000 1.000000 8.000000 1.000000 2.718282
    exp3
7.389056

then R flattens the result.  Weird.

 - Godmar




More information about the R-help mailing list