假设我有一组可能定义也可能没有定义的变量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
如果在未实例化x时调用了
test(x,y)
,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"
我猜测失败是由于它没有在正确的环境中查看。知道如何使它正常工作吗?
最佳答案
您可以指定首先要在哪个环境中运行:
test <- function(a,b) {
print(exists(as.character(substitute(a)), envir=parent.frame()))
if (!exists(as.character(substitute(a)), envir=parent.frame())) {a <- 0}
ifelse(a > b, "hello", "world")
}
这条路:
y <- 10
test(x,y)
# [1] FALSE
# [1] "world"
x <- 11
test(x,y)
#[1] TRUE
#[1] "hello"
rm(list=ls())
test <- function(a,b) {
print(exists(as.character(substitute(a)), envir=parent.frame()))
if (!exists(as.character(substitute(a)), envir=parent.frame())) {a <- 0}
ifelse(a > b, "hello", "world")
}
blah <- function() { x <- 11; y <- 10; test(x,y)}
blah()
#[1] TRUE
#[1] "hello"