Search code examples
rglobal-variables

How to use a value not in the scope of a function?


How to access variables defined outside the scope of a function.

foo <- "bar"

f <- function(){
  print(foo)
}

I should be able to print "bar"


Solution

  • You can use get():

    foo <- "bar"
    
    test <- function(){
      print(get("foo", envir = .GlobalEnv))
    }
    
    > test()
    [1] "bar"