0

I'm trying to figure out how to allow a function to directly alter or create variables in its parent environment, whether the parent environment is the global environment or another function.

For example if I have a function

my_fun <- function(){
  a <- 1
}

I would like a call to my_fun() to produce the same results as doing a <- 1.

I know that one way to do this is by using parent.frame as per below but I would prefer a method that doesn't involve rewriting every variable assignment.

my_fun <- function(){
  env = parent.frame()
  env$a <- 1
}
NGaffney
  • 1,542
  • 1
  • 15
  • 16

1 Answers1

6

Try with:

 g <- function(env = parent.frame()) with(env, { b <- 1 })

 g()

 b
 ## [1] 1

Note that normally it is preferable to pass the variables as return values rather than directly create them in the parent frame. If you have many variables to return you can always return them in a list, e.g. h <- function() list(a = 1, b = 2); result <- h() Now result$a and result$b have the values of a and b.

Also see Function returning more than one value.

Community
  • 1
  • 1
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341