Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: test what objects a function takes from the enclosing environment [duplicate]

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
like image 530
Nairolf Avatar asked Oct 15 '22 15:10

Nairolf


1 Answers

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).

like image 170
divibisan Avatar answered Nov 03 '22 07:11

divibisan