181

I am poking into the manuals, I wanted to ask the community: How can we set global variables inside a function?

0

3 Answers 3

209

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

3
  • 58
    This approach actually does not save in global environment, but instead in the parent scope. Sometimes parent scope will be the same as the global environment, though in some cases with lots of nested functions it won't. Jun 25, 2015 at 14:42
  • 6
    Why is assign preferred to <<-?
    – Jasha
    Apr 24, 2019 at 19:01
  • 5
    @Jasha <<- will search up the chain of enclosures up to the global environment and assign to the first matching variable it finds. Hypothetically, if you have a function f() nested in a closure g() and a exists in g(), then using a <<- in f() will assign to a in g(), not to the global environment. Oftentimes, this is what you want, however.
    – Bob
    Aug 12, 2019 at 0:02
124

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value
1
16

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

Not the answer you're looking for? Browse other questions tagged or ask your own question.