R-检查函数中对象的存在性

R-检查函数中对象的存在性,r,error-checking,R,Error Checking,假设我有一组变量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)包装在blah函数中。它找不到现有的变量 rm(list=ls())

假设我有一组变量
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)
包装在
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"
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")  
}

test为什么不使用
if(missing(a))a@RichardScriven
missing()
仅测试是否向该参数传递了“某物”。它并没有检查思维是否指向了一个有效的对象
missing(a)
x
为变量和非变量时都将返回TRUE。对于
test(,y)
它将返回TRUE,我认为您真正的问题是如何用不存在的变量的代码结束。我可能会重新思考导致这种情况发生的代码。这段代码的上下文是什么?我正在尝试使用helper函数进行大量的动态命名。业务需求代码。谢谢。这是我认为缺少的,但我不知道如何让它看起来像父母的框架。关于环境框架如何工作,是否有更好的文档?我觉得R的帮助不是很有用。你好,Shuo,我向你推荐@Hadley'Advanced R'书,可以在网上找到。他很好地解释了envrionnment在R中的工作原理。这个链接也包含了一些解释:@Shuo-我发现
sys.frame
帮助页面信息量很大。哈德利的书很好
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"