Skip to content

Global variables

1 message · Kenn Konstabel

#
On Fri, May 4, 2012 at 3:06 PM, Luis Goncalves <lgoncalves at gmail.com> wrote:
findGlobals helps you find the global variables in a function but it
does nothing with them. That is, it shows you something *about* a
function but does nothing *with* a function.

  findGlobals(square_without_globals, merge=FALSE)

shows you that you use 3 global variables in your function:

$functions
[1] "^" "{"

$variables
[1] "y"

Now it's up 2 you how you use this information. You would probably
like to use ^ and { (global variables) in your function but maybe not
y. So you can edit your function and leave y out or add y as an
argument.
Yes but ... in R, functions are also "variables", and you would
probably like some "global" functions (`+` or `(`) to be visible. You
can modify your function's environment so that it would access only
functions from certain packages (e.g base) and/or nothing from the
global workspace; that is what is done when functions are included in
packages.

Otherwise, I agree that it is best to avoid global variables and when
you use them, they should be "declared":

      square <- function (x) {
          # beware! y is used here as a "global variable"
          y^2
      }