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

William Revelle lists at revelle.net
Thu Jul 9 05:01:21 CEST 2009


Mark and Jason,




At 7:23 PM -0700 7/8/09, Mark Knecht wrote:
>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"
>  >


?list

e.g.,

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


Bill

-- 
William Revelle		http://personality-project.org/revelle.html
Professor			http://personality-project.org/personality.html
Department of Psychology             http://www.wcas.northwestern.edu/psych/
Northwestern University	http://www.northwestern.edu/
Attend  ISSID/ARP:2009               http://issid.org/issid.2009/




More information about the R-help mailing list