R 范围界定问题:对象存在但我无法对其执行任何操作

R scoping question: Object exists but I can't do anything with it

我想将一个函数的值提供给我在第一个函数中调用的另一个函数,但我似乎无法正确确定范围。至关重要的是,这两个功能是分开定义的。这是一个例子:

little_fun <- function(){
    print(paste("CheckNumber exists in parent frame =", exists("CheckNumber", where = parent.frame())))
    print(paste("CheckNumber exists in current frame =", exists("CheckNumber")))
    if(exists("CheckNumber", where = parent.frame())){
        print(CheckNumber + 2)
    }
}

运行 little_fun() 本身 returns

[1] "CheckNumber exists in parent frame = FALSE"
[1] "CheckNumber exists in current frame = FALSE"

这是我所期望的。但是,我想创建一个更复杂的函数,在内部调用 little_fun。

big_fun <- function(y){
    CheckNumber <- 5
        little_fun()
}

调用 big_fun returns 这个:

[1] "CheckNumber exists in parent frame = TRUE"
[1] "CheckNumber exists in current frame = FALSE"
 Error in print(CheckNumber + 2) : object 'CheckNumber' not found

CheckNumber 存在于父框架中但不存在于当前框架中,这对我来说很有意义。但是 CheckNumber 怎么可能存在于父框架中却不能添加到 2 中呢?我以为 R 会一直爬环境树,直到找到它需要的变量。这是怎么回事?

要注意的是 CheckNumber 存在于父 frame 中(从调用 little_fun 的地方)但不存在于 parent environment 中(其中 little_fun 已定义)。

使用 little_fun 中的附加代码进行测试:

little_fun <- function(){
    print(paste("CheckNumber exists in parent frame =",
                exists("CheckNumber", where = parent.frame())))
    ## present in parent environment?
    print(paste("CheckNumber exists in parent environment =",
                exists("CheckNumber", where = parent.env(environment()))))
    print(paste("CheckNumber exists in current frame =", exists("CheckNumber")))
    if(exists("CheckNumber", where = parent.frame())){
        print(CheckNumber + 2)
    }
}

要使 CheckNumber 可用,请在与 little_fun 相同或更高级别的环境中定义它,而不是在兄弟环境中(big_funlittle fun 在全局环境中的兄弟环境环境,除非你在 big_fun).

中定义 little_fun

无论如何,将值作为函数参数提供 - little_fun(CheckNumber = 5) - 将防止函数在父环境中摸索 same-named 变量。除了函数参数之外,依赖于变量的函数不容易 re-use 用于其他代码。

Chapter 7 "Environments" of Hadley Wickhams Advanced R中的背景解释。)