[英]In R, how do I evaluate an expression in a specific environment within a function?
[英]How do I test for existence of a variable within a function's environment?
给定函数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
之外的脚本中的其他位置定义了b
如何使f(-5)
返回FALSE
?
我希望这与exists()
的where
参数有关exists()
但我无法弄清楚调用此参数的适当环境是什么。 我仍然没有把头完全包裹在R的环境中......
谢谢!
只需使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.