I am poking into the manuals, I wanted to ask the community: How can we set global variables inside a function?
Asked
Active
Viewed 1.8e+01k times
3 Answers
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.

Christian
- 25,249
- 40
- 134
- 225

Dirk Eddelbuettel
- 360,940
- 56
- 644
- 725
-
58This 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. – LunaticSoul Jun 25 '15 at 14:42
-
6Why is `assign` preferred to `<<-`? – Jasha Apr 24 '19 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 '19 at 00: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

Christian
- 25,249
- 40
- 134
- 225
-
1see 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
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.

fitzberg
- 333
- 3
- 10