繁体   English   中英

条件是用户定义的function中存在object,而不是R中的全局环境

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

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

我想用 object 的存在来做条件语句。

如果 object variable在 function 中定义,则打印TRUE ,否则打印FALSE

在这种情况下,建议使用exists function。 如果之前未定义该variable ,则 function 将打印FALSE

但是,如果 object 未在function中定义,则exists function 会自动查找全局环境。 如果我之前在全局环境中定义了 object ,那么exists function 将始终打印TRUE

我只想根据 function 中的环境而不是全局环境来设置条件。

我非常感谢您的帮助。

存在 function 中存在“where”和“envir” arguments,请参见?exists 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变量,通常与用户定义的 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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM