1

In R, when I want to modify global variable in function, I do it like this:

myfun <- function ()
{
    a <<- 1
    # .. later.. more complex code
    a <<- 2
    a <<- 3
}

I don't like having to specify <<- instead <- all the time. I am not used to it and I always forget. Is it in R somehow possible to declare variable as global just once? E.g. something along the lines:

myfun <- function ()
{
    global a

    a <- 1 # modify global var
    # .. later.. more complex code
    a <- 2 # modify global var
    a <- 3 # modify global var
}

PS: I do not see how this would be a duplicate of the proposed question. Please expand in an answer to explain.

Tomas
  • 57,621
  • 49
  • 238
  • 373
  • Possible duplicate of [Set a functions environment to that of the calling environment (parent.frame) from within function](https://stackoverflow.com/questions/23890522/set-a-functions-environment-to-that-of-the-calling-environment-parent-frame-fr) – Oliver Nov 04 '19 at 23:47
  • [Global and local variables in R](https://stackoverflow.com/questions/10904124/global-and-local-variables-in-r) might be useful to check. – deepseefan Nov 04 '19 at 23:52
  • @deepseefan checked that one, there's no answer to this, thanks. – Tomas Nov 04 '19 at 23:53
  • @Oliver I do not see how this would be a duplicate of that question. Please expand in an answer to explain. – Tomas Nov 04 '19 at 23:54
  • I'm not sure about the specifics dictating your code complexity and the use of `global a`, but what if you take `global a` outside of the function (global environment), and do whatever you want to do with `a` within the function and if you want to modify the global `a` in the end, use the solution proposed by @Ronak. – deepseefan Nov 05 '19 at 00:09
  • 4
    "I don't like having to specify <<- instead <- all the time. I am not used to it and I always forget." -- good. – Hong Ooi Nov 05 '19 at 01:47

1 Answers1

1

Why do you need <<- to update a all the time in global environment in the function ? Use it only once at the end of the function to update the global variable.

myfun <- function () {
  a <- 1
  # .. later.. more complex code
  a <- 2
  a <<- 3
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • the code is way more complex to be thinking about the *last* occurence... but perhaps `a <<- a` at the end of the function could work? Still hoping for something more elegant though. Thanks! – Tomas Nov 04 '19 at 23:56