【问题标题】:How do I test for existence of a variable within a function's environment?如何测试函数环境中是否存在变量?
【发布时间】:2015-06-28 02:27:45
【问题描述】:

给定函数f()如下:

f = function(a) {
  if(a > 0) b = 2
  c = exists('b')
  return(c)
}

如何指定exists() 函数只能在函数f 内搜索?

在空白环境中,调用f(-5) 将返回FALSE,但如果我这样做了

b = "hello"
f(-5)

然后我得到TRUE。我如何让f(-5) 返回FALSE,即使用户在函数f 之外的脚本中其他地方定义了b

我预计这与exists()where 参数有关,但我无法弄清楚调用此参数的正确环境是什么。我还没有完全了解 R 中的环境......

谢谢!

【问题讨论】:

    标签: r function environment


    【解决方案1】:

    只要使用exists的inherits=参数即可。有关更多信息,请参阅?exists 帮助页面

    b <- 100
    f <- function(a) {
      if(a > 0) b <- 2
      c <- exists('b', inherits=FALSE)
      return(c)
    }
    f(5)
    # [1] TRUE
    f(-5)
    # [1] FALSE
    

    【讨论】:

    • 天哪:RTFM 又赢了! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2021-12-08
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多