【问题标题】:R - checking for existence of objects in a functionR - 检查函数中是否存在对象
【发布时间】:2015-01-13 05:24:35
【问题描述】:

假设我有一组变量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"

我猜失败是因为它没有在正确的环境中寻找。知道如何才能使其正常工作吗?

【问题讨论】:

  • 为什么不用if(missing(a)) a &lt;- 0 而不是exists?这是检查缺失参数的正确方法,而不是从其他环境中提取/尝试在其他环境中定位它们
  • @RichardScriven missing() 仅测试是否将“某物”传递给该参数。它不检查认为实际上指向一个有效对象。 missing(a) 将在 x 是变量和不是变量时返回 TRUE。对于test(,y),它将返回 TRUE
  • 我认为你真正的问题是你如何结束不存在的变量的代码。我可能会重新考虑导致这种情况发生的代码。这段代码的上下文是什么?
  • 我正在尝试做很多动态命名和使用辅助函数。代码的业务需求。

标签: r error-checking


【解决方案1】:

您可以指定首先查看的环境:

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 帮助很有用。
  • 你好 Shuo,我会向你推荐 @Hadley 'Advanced R' 的书,可以在网上找到。他极大地解释了环境在 R 中是如何工作的。这个链接也包含一些解释:stackoverflow.com/questions/7439110/…
  • @Shuo - 我发现sys.frame 帮助页面信息量很大。而且哈德利的书很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2013-09-26
  • 2016-01-17
  • 1970-01-01
相关资源
最近更新 更多