[R] Re use objects from within a custom made function

Daniel Nordlund djnordlund at verizon.net
Tue Oct 13 01:49:18 CEST 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Stropharia
> Sent: Monday, October 12, 2009 4:07 PM
> To: r-help at r-project.org
> Subject: [R] Re use objects from within a custom made function
> 
> 
> Hi everyone,
> 
> i'm having a problem extracting objects out of functions i've 
> created, so i
> can use them for further analysis. Here's a small example:
> 
> # ---------------------------
> test <- function(i, j){
> 	x <- i:j
> 	y <- i*j
> 	z <- i/j
> 	return(x,y,z)
> }
> # ---------------------------
> 
> This returns the 3 objects as $x, $y and $z. I cannot, 
> however, access these
> objects individually by typing for example:
> 
> test$x
> 
> I know i can do this by adding an extra arrow head to the 
> assignment arrow
> (<<-), but I am sure that is not how it is done in some of 
> the established R
> functions (like when calling lm$coef out of the lm function). 
> Is there a
> simple command i've omitted from the function that allows 
> access to objects
> inside it?
> 
> Thanks in advance,
> 
> Steve
> -- 

Steve,

I see a couple of problems (at least from my perspective).  If you ever got
your function to run, you would see a warning stating that returning
multiple objects is deprecated.  In your example of using the function, you
don't call it with any parameters, and the definition has no default values.
I also would be inclined to assign the results of the function call to a
variable/object and access the values from there. 

So I would approach your problem as follows:

test <- function(i, j){
	x <- i:j
	y <- i*j
	z <- i/j
	list(x=x, y=y, z=z)
}

my.result <- test(1,4)
> my.result$x
[1] 1 2 3 4
>

If you don't want to assign the output of test() to an object, then you will
need to do something like

test(1,4)$x

But this is inefficient because each time you access one of the components,
you need to rerun the function.

Hope this is helpful,

Dan

Daniel Nordlund
Bothell, WA USA




More information about the R-help mailing list