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

Shu*_*huo 4 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
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)

我猜这次失败的原因是它没有找到合适的环境.知道如何让这个工作正常吗?

Col*_*vel 5

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

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)

  • 您好Shuo,我会向您推荐@Hadley'Advanced R'书,可在网上找到.他非常了解环境如何在R中运作.此链接还包含一些解释:http://stackoverflow.com/questions/7439110/what-is-the-difference-between-parent-frame-and-parent-env-在-R-怎么办,他们 (3认同)