I am poking into the manuals, I wanted to ask the community: How can we set global variables inside a function?
3 Answers
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.
-
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. Jun 25, 2015 at 14:42
-
6
-
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 functionf()
nested in a closureg()
anda
exists ing()
, then usinga <<-
inf()
will assign toa
ing()
, not to the global environment. Oftentimes, this is what you want, however.– BobAug 12, 2019 at 0:02
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
-
1see also the accepted answer of this post: stackoverflow.com/questions/3969852/… for updating dataframes within a function Nov 7, 2019 at 23:58
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.