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

Petr PIKAL petr.pikal at precheza.cz
Thu Jul 9 10:50:29 CEST 2009


Hi

r-help-bounces at r-project.org napsal dne 09.07.2009 02:57:33:

> 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.

Not so weird. What do you expect from

c(1:5, 10:20, 30:50)

That is basically what your function do. With slight modification you can 
get tabular output without mapply

multipleoutput <- function (x) {
result.s <- x^2
result.c <- x^3
result.e <- exp(x)
cbind(square=result.s, cube=result.c, exp=result.e)
}

If the output could be mixed type }numeric, character, ...) use data.frame 
instead of cbind

Regards
Petr


> 
>  - Godmar
> 
> ______________________________________________
> R-help at r-project.org 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.




More information about the R-help mailing list