条件是对象存在于用户定义的函数中,而不是在 R 的全局环境中

Condition on the existence of the object in the User-defined function, not in the Global environment in R

我正在 R 中构建用户定义的函数。

我想用对象存在来做条件语句。

如果函数中定义了对象variable,则打印TRUE,否则,则FALSE.

在这种情况下,建议使用exists功能。如果之前没有定义 variable,该函数将打印 FALSE.

但是,如果对象没有在function中定义,exists函数会自动寻找全局环境。如果我之前在全局环境中定义了对象,那么 exists 函数将始终打印 TRUE.

我只想让条件依赖于函数中的环境,而不是全局环境。

非常感谢你的帮助。

exists 函数有“where”和“envir”参数,参见?exists

f <- function(x){
  if(is.numeric(x)) y <- x + 2
  exists(x = "y", where = -1)
}
f("a")
[1] FALSE
f(1)
[1] TRUE

或者,使用 envir 参数:

f <- function(x){
  if(is.numeric(x)) y <- x + 2
  exists(x = "y", envir = rlang::current_env())
}

但是,在实际情况下,创建一个 NULL 变量可能更可取,通常与用户定义的空合并运算符 (%||%) 配对,以便稍后指定默认值。

f <- function(x){
  y <- if(is.numeric(x)) x + 2 else NULL
  !is.null(y)
}
# same as
f <- function(x){
  y <- if(is.numeric(x)) x + 2
  !is.null(y)
}