Updated: 2022-04-12

Several nice blogs and references on the net to read on this stuff. Among those:

This discussion from StackOverflow and here explains nicely with example on the difference between parent.env() and parent.frame(). Hadley wrote in Advanced R that use parent.env() to find… surprise! surprise! To the parent of an environment!

sys.nframe()

To know the current dept of an environment, use sys.nframe(). The available object in the specific environment can be accessed with sys.nframe() as well. For instance, to access all the objects in the environment of a second call stack in a nexted call.

xx <- sys.nframe()[[2]]

sys.frames()

Another useful options is sys.frames()[[1]] to access the environment of the first calling function. It’s like using parent.frame() if you don’t have a nested functions. But once your functions are nested, sys.frames() will be useful to access the first calling function.

This is how I use it to assign a value to an object back to the calling function:

main_function <- function(var, val){
  sub_function(var, val)
}

sub_function <- function(var, val){
  is_assign_var(var, val)
}

is_assign_var <- function(var, val){
  assign(var, val, envir = sys.frames()[[1]])
}

If you don’t have a nested function then using parent.frame() or sys.frames()[[1]] will be equivalent.

main_function <- function(var, val){
  is_assign_var_01()
  is_assign_var_02()
}

is_assign_var_01 <- function(var, val){
  assign(var, val, envir = parent.frame())
}

is_assign_var_02 <- function(var, val){
  assign(var, val, envir = as.environment(sys.frames()[[1]]))
}
comments powered by Disqus