[EMAIL PROTECTED] 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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to