Assume, I create a parent's parent environment (E2 <= environment E1 <= environmet E) of an environment (E). My questions is, whether E2 is also parent to E. To me it was clear, that the answer was yes, but the following code seems to state the opposite.
What is wrong? See the last line in the reproducible example below, where print(parent-parent
) yields
# [1] FALSE # I would expect a TRUE here!!
From the docs ?parent.env
If one follows the chain of enclosures found by repeatedly calling parent.env from any environment, eventually one reaches the empty environment emptyenv(), into which nothing may be assigned.
subfun0 <- function() {
e <- parent.frame()
attr(e, "name") <- "my_env"
assign("my_env", 1,
envir = parent.frame(),
inherits = FALSE, immediate = TRUE)
return(NULL)
}
subsubfun <- function() {
print(" subsubfun")
print(" =========")
print(exists("my_env"))
print(exists("my_env", parent.frame()))
env <- parent.frame()
print(exists("my_env", parent.env(env)))
# print(parent.env(env)) # <environment: R_GlobalEnv>??
return(NULL)
}
subfun <- function() {
print(" subfun")
print(" ======")
print(exists("my_env"))
print(exists("my_env", parent.frame()))
env <- parent.frame()
print(exists("my_env", parent.env(env)))
subsubfun()
return(NULL)
}
fun1 <- function() {
print("fun1")
print("====")
subfun0()
print(exists("my_env"))
print(exists("my_env", parent.frame()))
env <- parent.frame()
print(exists("my_env", parent.env(env)))
subfun()
return(NULL)
}
fun1()
# [1] "fun1"
# [1] "===="
# [1] TRUE # OK
# [1] FALSE
# [1] FALSE
# [1] " subfun"
# [1] " ======"
# [1] FALSE
# [1] TRUE # OK
# [1] FALSE
# [1] " subsubfun"
# [1] " ========="
# [1] FALSE
# [1] FALSE
# [1] FALSE # I would expect a TRUE here!!