When writing functions in R, I usually build them from code I've already written. And R doesn't have a local scope, meaning the function can be accessing variables defined outside its scope and parameters. This is annoying because you want to make all variables local to the function for reusability.
The package codetools provides the function 'findGlobals' which can check functions to see if they are using any global variables. For example, I write:
x <- 2
foo <- function(y) { return(x*2) }
print(foo(5))
This would print 4 and not 10.
If we write the following function (sourced from http://stackoverflow.com/questions/6216968/r-force-local-scope )
checkStrict <- function(f, silent=FALSE) {
vars <- codetools::findGlobals(f)
found <- !vapply(vars, exists, logical(1), envir=as.environment(2))
if (!silent && any(found)) {
warning("global variables used: ", paste(names(found)[found], collapse=', '))
return(invisible(FALSE))
}
!any(found)
}
We can apply this to our function 'foo':
checkStrict(foo)
Resulting in the output:
Warning message:
In checkStrict(foo) : global variables used: x
R - Forcing local scope on a function
Advertisemen
Advertisemen
Tidak ada komentar:
Posting Komentar