4

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()
2

2 Answers 2

11

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
5
  • 1
    Perfect. Yeah the character comparison bothered me but didn't think to use identical and compare the environments directly. Sep 5, 2013 at 13:59
  • @eddi true. Perhaps globalenv() would be safer. I'll update. Sep 5, 2013 at 15:49
  • @hadley True, true. This-is-R. Do you have a bulletproof suggestion? Sep 5, 2013 at 21:02
  • @SimonO101 don't worry about people overriding functions - i.e. you don't need the part of your answer after the first code block.
    – hadley
    Sep 6, 2013 at 15:39
  • I thought I'd show the context this was used in for future searchers. Here is the inclusion of this function in a package. Here is how I used it as an argument to a function (see the open argument). Sep 6, 2013 at 20:16
1

Maybe sys.nframe?

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

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

fun()
#[1] FALSE
2
  • sys.nframe() will never return zero inside a function body, right? Sep 6, 2013 at 1:42
  • Of course not, only when called in the global environment. And detecting that was the task, no? Detecting if a function is called in the global environment is a different task.
    – Roland
    Sep 6, 2013 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.