检查是否定义了一组变量&执行环境中不是NULL

时间:2017-08-11 08:00:54

标签: r scope

在一个函数中,我想检查本地范围中是否存在变量名(不查看父envs),如果它们存在,则不是NULL。下面的工作示例,但我想知道是否有一种比我现在的错综复杂的公开电话更优雅的方式:

a = 1
f <- function () {
  source(textConnection("b <- 2;c <- NULL"), local = TRUE)
  vars <- c("a", "b", "c", "d")
  # a, c & d are missing || NULL in local scope
  # (a is missing as it was defined outside function env)
  # create a logical vector where TRUE means missing/NULL
  missing_vars <- sapply(vars, function(x)
    is.null(get0(x, inherits = FALSE, envir = parent.env(environment()))))
  print(missing_vars)       
  # try to auto-detect appropriate values for missing vars,
  # then call the original function
  # ...      
}    

已解决 - 按照Roland的回答重写示例:

a <- 1
g <- function () {
  myenv <- new.env()
  source(textConnection("b <- 2;c <- NULL"), local = myenv)
  vars <- c("a", "b", "c", "d")
  missing_vars <- sapply(vars, function(x) is.null(myenv[[x]]))
  print(missing_vars)       
}

背景: 对于需要一长串参数(水文建模)的函数,我正在编写一个包装器,允许用户在简单的R脚本中将所需的参数定义为变量。这个&#34;配置&#34;然后将脚本输入到函数env中。如果某些变量丢失或设置为NULL,我有一些代码可以在调用原始函数之前自动检测这些值。

0 个答案:

没有答案