[R] Global variables
Kenn Konstabel
lebatsnok at gmail.com
Mon May 7 00:23:46 CEST 2012
On Fri, May 4, 2012 at 3:06 PM, Luis Goncalves <lgoncalves at gmail.com> wrote:
>
>
> On May 2 2011, 3:02 pm, Kenn Konstabel <lebats... at gmail.com> wrote:
>> On Mon, May 2, 2011 at 2:19 PM, abhagwat <bhagwatadi... at gmail.com> wrote:
>> > Well, what would be really helpful is to restrict the scope of all
>> > non-function variables, but keep a global for scope of all function
>> >variables. Then, you still have access to all loaded functions, but you
>> > don't mix upvariables.
>>
>> > How would one do that?
>>
>> But what's the real motivation for this? It could be useful for
>> ensuring that there are no unexpectedglobalvariablesin your code
>> but you can do it using findGlobals in codetools package.
>>
>> fun <- function() mean(x)
>> findGlobals(fun, merge=FALSE)
>>
>> Kenn
>>
>
> Kenn,
>
> I tried your method :
>
> library(codetools)
>
> square <- function (x) {
> y^2
> }
>
> y <- c(1, 3, 5, 9)
>
> square_without_globals <- function (x) {
> y^2
> }
>
> findGlobals(square_without_globals, merge=FALSE)
>
> but still get global variables in square_without_globals():
>
> > source('R_test_block_global_variables.R')
> > y
> [1] 1 3 5 9
> > square(7)
> [1] 1 9 25 81
> > square_without_globals(7)
> [1] 1 9 25 81
>
> What have I done wrong?
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.
> (PS: I am an R novice, coming from the Matlab world. In Matlab, you
> have to declare global variables to be used in a function explicitly.
> Isn't it good programming practice (in ANY language) to NOT allow
> global variable visibility as a default? Leads to a lot less hard-to-
> find bugs!!!)
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
}
More information about the R-help
mailing list