假设我有一组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
Run Code Online (Sandbox Code Playgroud)
如果我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"
Run Code Online (Sandbox Code Playgroud)
但是,如果我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"
Run Code Online (Sandbox Code Playgroud)
我猜这次失败的原因是它没有找到合适的环境.知道如何让这个工作正常吗?
您可以指定首先查找的环境:
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")
}
Run Code Online (Sandbox Code Playgroud)
这条路:
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1075 次 |
| 最近记录: |