[R] Is there a way to figure out what nonlocal variables and functions have been used in a function?

Sharpie chuck at sharpsteen.net
Fri Feb 12 23:35:04 CET 2010

blue sky wrote:
> I don't what '{' and functions available in R libraries. I can
> manually exclude '{'. Is there an easy way to exclude the functions
> from R libraries?

Well, you could write a function, say isPackaged( name ), that returns TRUE
or FALSE depending on whether the object matching `name` is part of a
"package:" namespace.  Of the top of my head, a quick version would use

  isPackaged <- function( name ){

    # find() returns the environment that contains 
    # the object specified by `name`

    container <- find( name )

    # Return the results of a check to see if the container 
    # is a package by looking for the string 'package:' to
    # be at the start of the result returned by find()

      grepl( '^(package:)', container ) 


You could then use a function like Filter() to separate the results of
findglobals() into packaged and non-packaged variables:

f=function() {print('in f')}
g=function() {f(); print(x)}

require( codetools )

globals <- findGlobals( g )

Filter( isPackaged, globals )
[1] "{"     "print"

Filter( Negate( isPackaged ), globals )
[1] "f" "x"

There are probably corner cases that won't be handled by the above code, but
it should be a start.

Good luck!

View this message in context: http://n4.nabble.com/Is-there-a-way-to-figure-out-what-nonlocal-variables-and-functions-have-been-used-in-a-function-tp1478673p1490499.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list