[R] finding global variables in a function containing formulae
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Nov 3 10:39:57 CET 2012
On Thu, Nov 1, 2012 at 2:04 PM, Hafen, Ryan P <Ryan.Hafen at pnnl.gov> wrote:
> I need to find all global variables being used in a function and findGlobals() in the codetools package works quite nicely. However, I am not able to find variables that are used in formulae. Simply avoiding formulae in functions is not an option because I do not have control over what functions this will be applied to.
>
> Here is an example to illustrate:
>
> library(codetools)
>
> xGlobal <- rnorm(10)
> yGlobal <- rnorm(10)
>
> plotFn1 <- function() {
> plot(yGlobal ~ xGlobal)
> }
>
> plotFn2 <- function() {
> y <- yGlobal
> x <- xGlobal
> plot(y ~ x)
> }
>
> plotFn3 <- function() {
> plot(xGlobal, yGlobal)
> }
>
> findGlobals(plotFn1, merge=FALSE)$variables
> # character(0)
> findGlobals(plotFn2, merge=FALSE)$variables
> # [1] "xGlobal" "yGlobal"
> findGlobals(plotFn3, merge=FALSE)$variables
> # [1] "xGlobal" "yGlobal"
>
> I would like to find that plotFn1 also uses globals xGlobal and yGlobal. Any suggestions on how I might do this?
If this is only being applied to your own functions then we can have a
convention when writing them to help it in which we "declare" such
variables so that findGlobals can locate them:
plotFn1 <- function() {
xGlobal; yGlobal
plot(yGlobal ~ xGlobal)
}
findGlobals(plotFn1)
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list