Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if environment is global environment

Tags:

r

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()
like image 511
Tyler Rinker Avatar asked Dec 15 '22 06:12

Tyler Rinker


2 Answers

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
like image 151
Simon O'Hanlon Avatar answered Dec 17 '22 18:12

Simon O'Hanlon


Maybe sys.nframe?

sys.nframe() == 0L
#[1] TRUE

fun <- function() {
  sys.nframe() == 0L
}

fun()
#[1] FALSE
like image 26
Roland Avatar answered Dec 17 '22 20:12

Roland