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"

Upvotes: 0

Views: 57

Answers (2)

Roland
Roland

Reputation: 132989

Your code works as written:

foo <- "bar"

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

f()
#[1] "bar"

Of course, it's not good practice to rely on scoping. You should instead pass variables as function parameters.

Upvotes: 3

LAP
LAP

Reputation: 6695

You can use get():

foo <- "bar"

test <- function(){
  print(get("foo", envir = .GlobalEnv))
}

> test()
[1] "bar"

Upvotes: 4

Related Questions