Sometimes it may be useful to detect if the environment is the global environment or not and act accordingly. I have come up with what I believe is a way to detect the environment and test if it's the global environment. I just don't want to be reinventing the wheel if there's a better way or if this has holes etc. Is there some sort of built in R method to do what global_test
does below or a better approach?
global_test <- function() {
environmentName(parent.frame(n = 1)) == "R_GlobalEnv"
}
global_test()
lapply(1:10, function(i) {
global_test()
})
fun <- function() global_test()
fun()
I would simplify your life a little and use identical
:
global_test <- function() {
identical( parent.frame(n = 1) , globalenv() )
}
And I think this should be slightly 'safer' than doing a character comparison because you can do this:
e <- new.env()
attr(e,"name") <- "R_GlobalEnv"
# And then...
environmentName(e)
#[1] "R_GlobalEnv"
And as pointed out by @eddi, using .GlobalEnv
may also not be desirable because one can do:
.GlobalEnv <- 1
identical( parent.frame(n = 1) , .GlobalEnv )
#[1] FALSE
This use of identical
is in fact one of the examples from the help page on ?identical
:
## even for unusual R objects :
identical(.GlobalEnv, environment())
So even if we try to trick R the function still works:
e <- new.env()
attr(e,"name") <- "R_GlobalEnv"
.GlobalEnv <- 1
global_test()
#[1] TRUE
Maybe sys.nframe
?
sys.nframe() == 0L
#[1] TRUE
fun <- function() {
sys.nframe() == 0L
}
fun()
#[1] FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With