0

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!

doubleOK
  • 333
  • 4
  • 18

1 Answers1

1

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)

Community
  • 1
  • 1
Emil Rehhnberg
  • 811
  • 7
  • 4