Reputation: 371
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
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
Reputation: 6695
You can use get()
:
foo <- "bar"
test <- function(){
print(get("foo", envir = .GlobalEnv))
}
> test()
[1] "bar"
Upvotes: 4