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

时间:2022-06-29 23:12:58

Given the function f() as follows:

给定函数f()如下:

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

How do I specify that the exists() function should only search within the function f?

如何指定exists()函数只应在函数f中搜索?

With a blank environment, calling f(-5) will return FALSE as I would like, but if I do

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

b = "hello"
f(-5)

then I get TRUE. How do I get f(-5) to return FALSE even if the user has a b defined elsewhere in their script outside the function f?

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

I expect this has something to do with the where parameter of exists() but I can't figure out what is the proper environment to call for this parameter. I still haven't wrapped my head fully around environments in R...

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

Thanks!

1 个解决方案

#1


10  

Just use the inherits= parameter of exists. See the ?exists help page for more info

只需使用exists的inherits =参数即可。有关详细信息,请参阅?存在帮助页面

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

#1


10  

Just use the inherits= parameter of exists. See the ?exists help page for more info

只需使用exists的inherits =参数即可。有关详细信息,请参阅?存在帮助页面

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