如何在函数环境中测试变量的存在?

Cep*_*irk 7 environment r function

鉴于功能f()如下:

f = function(a) {
  if(a > 0) b = 2
  c = exists('b')
  return(c)
}
Run Code Online (Sandbox Code Playgroud)

如何指定该exists()函数只应在函数内搜索f

在空白的环境中,呼叫f(-5)FALSE按照我的意愿返回,但如果我这样做的话

b = "hello"
f(-5)
Run Code Online (Sandbox Code Playgroud)

然后我明白了TRUE.即使用户在函数外部的脚本中已经定义了其他地方,我该如何f(-5)返回?FALSEbf

我希望这与where参数有关,exists()但我无法弄清楚调用此参数的正确环境是什么.我仍然没有把头完全包裹在R的环境中......

谢谢!

MrF*_*ick 11

只需使用inherits=exists参数即可.有关?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
Run Code Online (Sandbox Code Playgroud)