> -----Original Message-----
> From: r-help-boun...@r-project.org 
> [mailto:r-help-boun...@r-project.org] On Behalf Of Stropharia
> Sent: Monday, October 12, 2009 4:07 PM
> To: r-help@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

______________________________________________
R-help@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.

Reply via email to