R:测试函数从封闭环境中获取哪些对象
R: test what objects a function takes from the enclosing environment
在定义 R 函数时,我有时会忘记它依赖于封闭环境中的对象。类似于:
a <- 1
fn <- function(x) x + a
如果这种情况无意中发生,可能会导致难以调试的问题。
有没有简单的方法来测试fn
是否使用封闭环境中的对象?
类似于:
test(fn=fn, args=list(x=1))
## --> uses 'a' from enclosing environment
一种可能性是使用 codetools
包中的 findGlobals
函数,该函数旨在:
Finds global functions and variables used by a closure
这适用于您的示例:
#install.packages('codetools')
codetools::findGlobals(fn)
[1] "+" "a"
如果我们在函数内部定义 a
,它就会消失:
fn <- function(x) {
a = 1
x + a
}
codetools::findGlobals(fn)
[1] "{" "+" "="
但我还没有在更复杂的事情中使用它,所以我不能说更复杂的功能会有多准确。文档附带以下警告:
The result is an approximation. R semantics only allow variables that might be local to be identified (and event that assumes no use of assign and rm).
在定义 R 函数时,我有时会忘记它依赖于封闭环境中的对象。类似于:
a <- 1
fn <- function(x) x + a
如果这种情况无意中发生,可能会导致难以调试的问题。
有没有简单的方法来测试fn
是否使用封闭环境中的对象?
类似于:
test(fn=fn, args=list(x=1))
## --> uses 'a' from enclosing environment
一种可能性是使用 codetools
包中的 findGlobals
函数,该函数旨在:
Finds global functions and variables used by a closure
这适用于您的示例:
#install.packages('codetools')
codetools::findGlobals(fn)
[1] "+" "a"
如果我们在函数内部定义 a
,它就会消失:
fn <- function(x) {
a = 1
x + a
}
codetools::findGlobals(fn)
[1] "{" "+" "="
但我还没有在更复杂的事情中使用它,所以我不能说更复杂的功能会有多准确。文档附带以下警告:
The result is an approximation. R semantics only allow variables that might be local to be identified (and event that assumes no use of assign and rm).