[R] How define global Variable?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Mon Nov 28 15:41:19 CET 2005


svenknueppel at reilich.net wrote:

> R> a <- "old"
> R> test <- function () { a <- "new" }
> R> test()
> R> a # shoud be "new"
> 
> This doesn't work. I would like to modify the variable "a" in a
> procedure. How can I do that.

  You may like to modify the variable, but who else wants you to?

Functions should have zero side effects whenever possible. Wanting to 
muck with global variables is a big red flag that something is wrong 
with your program. It will become hard to debug or follow what is going 
on. Imagine, in six weeks time you look at:

  a = "old"
  test()
  if (a == "new"){
    doSomething()
  }

  - well, its not obvious that 'a' could possibly have changed to "new". 
Sure you could look at test() and see, but then test() could call 
something else that calls something else and then somewhere else 'a' is 
set. It can make for very very messy code.

  The solution is to return anything that changes. Example:

  a = "old"

  test=function(){return(list(a="new"))}

  ttt = test()
  a = ttt$a

  That's probably the recommended way of returning multiple things from 
a function too - wrap them in a list and get them. Modifying global 
variables is very rarely the Right Thing.

  I'm sure someone will come up with a solution but it'll probably 
involve frames and environments and other messy magic language stuff you 
really dont want to get into. Keep It Simple, Sunshine.

Barry




More information about the R-help mailing list