When defining an R function, I sometimes miss that it relies on objects from the enclosing environment. Something like:
a <- 1
fn <- function(x) x + a
If this happens unintentionally, it can lead to problems which are difficult to debug.
Is there a simple way to test whether fn
uses objects from the enclosing environment?
Something like:
test(fn=fn, args=list(x=1))
## --> uses 'a' from enclosing environment
One possibility is to use the findGlobals
function from the codetools
package which is designed to:
Finds global functions and variables used by a closure
This works in your example:
#install.packages('codetools')
codetools::findGlobals(fn)
[1] "+" "a"
If we define a
inside the function, it goes away:
fn <- function(x) {
a = 1
x + a
}
codetools::findGlobals(fn)
[1] "{" "+" "="
But I haven't used it in anything more complex, so I can't say how accurate it will be with a more complex function. The docs come with the following caveat:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With