Environments in R, mapply and get

前端 未结 3 839
深忆病人
深忆病人 2021-01-22 17:51

Let x<-2 in the global env:

x <-2 
x
[1] 2

Let a be a function that defines another x locally and

3条回答
  •  故里飘歌
    2021-01-22 18:50

    The issue is an interplay with built-in C code. Namely, considering the following:

    fx <- function(x) environment()
    env <- NULL; fn <- function() { env <<- environment(); mapply(fx, 1)[[1]] }
    

    Then

    env2 <- fn()
    identical(env2, env)
    # [1] FALSE
    identical(parent.env(env2), env)
    # [1] FALSE
    identical(parent.env(env2), globalenv())
    # [1] TRUE
    

    More specifically, the problem lies in the underlying C code, which fails to consider executing environment, and hands it off to an as-is underlying C eval call which creates a temp environment branching directly off of R_GlobalEnv.

    Note this really is what is going on, since no level of stack nesting fixes the issue:

    env <- NULL; fn2 <- function() { env <<- environment(); (function() { mapply(fx, 1)[[1]] })() }
    identical(parent.env(fn2()), globalenv())
    # [1] TRUE
    

提交回复
热议问题