[R] reporting multiple objects out of a function

Paul Hiemstra paul.hiemstra at knmi.nl
Wed Oct 5 11:03:53 CEST 2011


On 10/05/2011 04:27 AM, andrewH wrote:
> Dear folks, 
>
> I’m trying to build a function to create and make available some variables I
> frequently use for testing purposes.  Suppose I have a function that takes
> some inputs and creates (internally) several named objects. Say, 
>
> fun1 <- function(x, y, z) {obj1 <- x; obj2 <- y; obj3 <- z
> <missing stuff>
> }
>
> Here is the challenge: After I run it, I want the objects to be available in
> the calling environment, but not necessarily in the global environment.  I
> want them to be individually available, not as part of a list or some larger
> object.  I can not figure out how to do this.  If I understand the situation
> correctly, I am trying to move several separate objects from the environment
> of the function to the environment in which the function was invoked (the
> “calling environment,” yes?).  
>
> I’m pretty sure there is a command to do this, but I’m not sure how to find
> it. Any help would be greatly appreciated – either on the necessary code, or
> on how to search for it, or a reference to a good discussion of this family
> of problems.
>
> Sincerely, andrewH
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/reporting-multiple-objects-out-of-a-function-tp3873380p3873380.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at 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.

Hi,

You can use the <<- operator. Although in the spirit of fortune(106),
"If <<- is the answer, rethink your question...". Why is it important
that your objects are not part of a larger object, which is standard
practice in R. You could also take a look at the attach() command:

bla = fun1(x,y,z)
attach(bla)

Note that in fun1 you do need to return your objects in a list. However,
I'm still not in favor of using this approach...

good luck,
Paul

-- 
Paul Hiemstra, Ph.D.
Global Climate Division
Royal Netherlands Meteorological Institute (KNMI)
Wilhelminalaan 10 | 3732 GK | De Bilt | Kamer B 3.39
P.O. Box 201 | 3730 AE | De Bilt
tel: +31 30 2206 494

http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770



More information about the R-help mailing list