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

Mark Knecht markknecht at gmail.com
Thu Jul 9 04:23:09 CEST 2009


On Wed, Jul 8, 2009 at 5:55 PM, Mark Knecht<markknecht at gmail.com> wrote:
> On Wed, Jul 8, 2009 at 5: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.
>>
>> 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)
>>
>> }
>>
>> Thanks again for all your help.
>>

<SNIP>

This version runs a bit better than my last and I find it a bit more
readable, but there's a warning for whatever the first computation is
inside the function that I'd like to understand.

- Mark

multipleoutput <- function(x) {
	answer = c("Squ"=0,"Cub"=0,"Exp"=0,"Fac"=0)
	answer$Squ=x^2
	answer$Cub<-x^3
	answer$Exp<-exp(x)
	answer$Fac<-factorial(x)
	return(answer)
}

X = data.frame("Squared"=0,"Cubed"=0,"Exp"=0,"Fac"=0)
X
mode(X)
names(X)

X[1,] <- multipleoutput(2)

X
class(X)

<PRODUCES>

> multipleoutput <- function(x) {
+ answer = c("Squ"=0,"Cub"=0,"Exp"=0,"Fac"=0)
+ answer$Squ=x^2
+ answer$Cub<-x^3
+ answer$Exp<-exp(x)
+ answer$Fac<-factorial(x)
+ return(answer)
+ }
>
> X = data.frame("Squared"=0,"Cubed"=0,"Exp"=0,"Fac"=0)
> X
  Squared Cubed Exp Fac
1       0     0   0   0
> mode(X)
[1] "list"
> names(X)
[1] "Squared" "Cubed"   "Exp"     "Fac"
>
> X[1,] <- multipleoutput(2)
Warning message:
In answer$Squ = x^2 : Coercing LHS to a list
>
> X
  Squared Cubed      Exp Fac
1       4     8 7.389056   2
> class(X)
[1] "data.frame"
>
>
>




More information about the R-help mailing list