Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...