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

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Jul 9 05:03:33 CEST 2009


Hi,

On Jul 8, 2009, at 8:34 PM, Jason Rupert 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.
>
> 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)
> 	
> }

There already have been some suggestions on how to do this the  
"normal" R way, so let's go ahead and use the "return a list" method  
(I think it's better than using the `c(squared=x^2, cubed=...)`).

Here's an interesting way to receive the assignments. Check out this  
function:

http://code.google.com/p/miscell/source/browse/rvalues/rvalues.r

With that ':=' function loaded, you could do this:

============
multipleout <- function(x) {
   list(squared=x^2, cubed=x^3, exponential=exp(x),
        factorial=factorial(x))
}

c(sq,cu,ex,fa) := multipleout(1:3)
show(sq)
[1] 1 4 9

show(cu)
[1]  1  8 27

show(ex)
[1]  2.718282  7.389056 20.085537

show(fa)
[1] 1 2 6

=============

[I can't remember how I stumbled onto this code for the ':=' function  
(I think it was from a thread on the BioC list about package updates)]

I'm not saying that you *should* do it this way, but it's kind of cool  
that you could ...

-steve

--
Steve Lianoglou
Graduate Student: Physiology, Biophysics and Systems Biology
Weill Medical College of Cornell University

Contact Info: http://cbio.mskcc.org/~lianos




More information about the R-help mailing list