假设我有一组x, y
可能定义或未定义的变量。这些变量被传递到一个名为test
.
y <- 10
test <- function(a,b) { ifelse(a > b, "hello", "world") }
test(x,y)
# Error in ifelse(a > b, "hello", "world") : object 'x' not found
如果我test(x,y)
在 x 尚未实例化时调用,R 将抛出“未找到对象'x'”错误。
如果我添加了存在检查,则该函数在从全局环境中调用它时会起作用
y <- 10
test <- function(a,b) {
print(exists(as.character(substitute(a))))
if (!exists(as.character(substitute(a)))) {a <- 0}
ifelse(a > b, "hello", "world")
}
test(x,y)
# [1] FALSE
# [1] "world"
x <- 11
test(x,y)
[1] TRUE
[1] "hello"
但是,如果我包装test(x,y)
在blah
函数中。它无法找到现有的变量。
rm(list=ls())
test <- function(a,b) {
print(exists(as.character(substitute(a))))
if (!exists(as.character(substitute(a)))) {a <- 0}
ifelse(a > b, "hello", "world")
}
blah <- function() { x <- 11; y <- 10; test(x,y)}
blah()
[1] FALSE -- expecting TRUE
[1] "world" -- expecting "hello"
我猜失败是因为它没有在正确的环境中寻找。知道我怎样才能让它正常工作吗?