Global variables in R


Question

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

1
125
11/22/2018 9:54:41 AM

Accepted Answer

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.

153
11/22/2018 9:56:32 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon