R - 检查函数中对象是否存在

标签 r error-checking

假设我有一组可能已定义或 undefined variable 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"

关于R - 检查函数中对象是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27910834/

相关文章:

r - 按固定距离缩小 SF 多边形

r - 如何使用 cumsum 但条件是 <0 然后使用 0

c++ - 有什么理由使用运行时断言而不是编译时断言吗?

r - 如何使用 quantmod 将自定义每小时数据绘制到 R 中?

r - ggplot 图例关键颜色和项目

c++ - C++如何防止在编译时调用一个以上的方法?

excel - 如何在 EPPlus 中关闭 Excel 应用程序对象的后台错误检查?

C:一种更安全的方法来检查函数中的缓冲区并附加到它?

arrays - 检查用户MATLAB是否重复输入坐标

每行随机数生成