168

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

Christian
  • 23,801
  • 35
  • 124
  • 210
Alphaneo
  • 11,431
  • 20
  • 68
  • 88

3 Answers3

194

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.

Christian
  • 23,801
  • 35
  • 124
  • 210
Dirk Eddelbuettel
  • 347,098
  • 55
  • 623
  • 708
115

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
Christian
  • 23,801
  • 35
  • 124
  • 210
  • 1
    see also the accepted answer of this post: https://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work for updating dataframes within a function – user1420372 Nov 07 '19 at 23:58
12

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.

fitzberg
  • 143
  • 1
  • 8