doubleOK
doubleOK

Reputation: 353

R: attach all of the variables local to the function to global environment after it executes

Suppose I get some function from a client

f <- function(x) {
  if (x) {
    y <- 0
  } else {
    y <- 1
  }
}

Since I get it from a client I cannot modify anything within f (aka substitute <- with <<-, or explicitly attach variables to the global environment).

Is there a way to somehow access all of the variables created within f with whatever values got assigned to them (after I ran it) from the global environment ? For example: if I ran

f(TRUE)

I would be able to access a variable "y" in the global environment and see that it is set to "0". I am not worried about overwriting anything in the global environment.

Thanks!

Upvotes: 0

Views: 328

Answers (2)

J_H
J_H

Reputation: 20435

1. change the function

I have to believe that deparse(f) gives enough information for defining a new identical function g. With that in hand, we could tack on print(ls()) and other code for dumping local vars.

2. run the function unaltered

Ok, suppose we want to run f exactly as-is. Let's see. In addition to argument x, we also (implicitly) passed in an environment, which f changes by creating a local y entry.

Define a new environment, a debugging variant, which logs writes such as creation of y. Have it report on those values in some convenient way, such as by mirroring all writes to the global env.

Upvotes: 0

Emil Rehhnberg
Emil Rehhnberg

Reputation: 1041

Option 1, pass in the parent environment:

f <- function(x, env = parent.frame()) {
  if (x) {
    env$y <- 0
  } else {
    env$y <- 1
  }
}

Option 2, use R's special assignment <<-

f <- function(x) {
  if (x) {
    y <<- 0
  } else {
    y <<- 1
  }
}

There's more options out there too. See topic: In R, how to make the variables inside a function available to the lower level function inside this function?(with, attach, environment)

Upvotes: 1

Related Questions