Skip to content

Global variables

3 messages · Aditya Bhagwat, Duncan Murdoch, Kenn Konstabel

#
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 up variables.

How would one do that?

Adi
Yes, but you probably shouldn't.  You would do it by setting the 
environment of the function to something that doesn't have the global 
environment as a parent, or grandparent, etc.  The only common examples 
of that are baseenv() and emptyenv().  For example,

x <- 1
f <- function() print(x)


--
View this message in context: http://r.789695.n4.nabble.com/Global-variables-tp3178242p3489796.html
Sent from the R help mailing list archive at Nabble.com.
#
On 02/05/2011 7:19 AM, abhagwat wrote:
You can't without low level modifications.  Before R has done the 
lookup, it doesn't know if an object is a function or not.  It can guess 
by usage, e.g. it can recognize that "print" should be a function in 
print(1) and it will ignore non-functions named "print", but it is very 
common in R code to do things like

fn <- print
fn(1)

and that would fail.  But if you want to experiment with the change, you 
can, because R is open source.   I doubt if you'll get much help unless 
you give a really convincing argument (on the R-devel list, not on this 
list) why to make the change.

Duncan Murdoch
#
On Mon, May 2, 2011 at 2:19 PM, abhagwat <bhagwataditya at gmail.com> wrote:
But what's the real motivation for this? It could be useful for
ensuring that there are no unexpected global variables in your code
but you can do it using findGlobals in codetools package.

fun <- function() mean(x)
findGlobals(fun, merge=FALSE)


Kenn