Inside an R function, how do I access the calling environment?

foo <- function() {
  # how to know what environment_of_caller is
}

caller <- function() {
  # environment_of_caller
  foo()
}

A function that I'm writing needs to the know the environment of its caller. Can that be done without passing the environment in as an argument?

Upvotes: 1

Views: 223

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270308

Assuming that you really need to do this, the function parent.frame() gives it.

foo <- function() {
  parent.frame()$a
}

caller <- function() {
  a <- 1
  foo()
}

caller()
## [1] 1

however, normally one would write it like this (only foo is changed) as it gives the desired functionality but also the flexibility to change the environment used.

foo <- function(envir = parent.frame()) {
  envir$a
}

caller <- function() {
  a <- 1
  foo()
}

caller()
## [1] 1

Upvotes: 4

Related Questions