[R] reporting multiple objects out of a function

Gabor Grothendieck ggrothendieck at gmail.com
Thu Oct 6 05:22:40 CEST 2011


On Wed, Oct 5, 2011 at 12:27 AM, andrewH <ahoerner at rprogress.org> 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.

If the question is how to write things into the calling environment
(also called the parent frame in R) then its like this:

fun1 <- function(x, y, z, env = parent.frame()) {
  env$x <- x
  env$y <- y
  env$z <- z
}
fun1(1, 2, 3)
x # 1

However, this seems very close to object oriented programming where
fun1 is a method and x, y and z are properties and might represent a
better organization of your program.  For example,

library(proto)
p <- proto(fun1 = function(., x, y, z) {
  .$x <- x
  .$y <- y
  .$z <- z
})

p$fun1(1, 2, 3) # set properties x, y, z
p$x # 1

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list