我正在尝试检查作为参数传递给函数的变量是否存在。根据对this问题的回答,我有以下内容:
myfunction <- function(x) {
stopifnot(exists(deparse(substitute(x))))
}
但是,如果参数是要评估的表达式,则它不起作用:
a=c(1:10)
myfunction(a+10)
如果参数不仅仅是变量,我怎样才能确保捕获不存在的变量?
答案 0 :(得分:1)
一个选项是组合match.call
(返回对函数的调用)和all.vars
(返回表达式中的名称)。试试这个:
fcn <- function(x) {
varnames <- all.vars(match.call())
for (x in varnames)
stopifnot(exists(x))
}
fcn(a) # returns error, as expected
#Error: exists(x) is not TRUE
# create "a"
a <- 2
fcn(a + 1) # no error returned since "a" exists
类似地,
fcn(a + b) # error returned since "b" does not exist
#Error: exists(x) is not TRUE
b <- 4
fcn(a + b) # no error since "b" now exists