[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
By design GNU R uses lexical scoping. Fortunately it allows for at least two ways to simulate dynamic scoping.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Let us start with the example code and next analyze it:
x <- “global”< o:p>
f1 <- function() cat(“f1:”, x, “\n”)
f2 <- function() cat(“f2:”, evalq(x, parent.frame()), “\n”)
fun <- function() {
x <- “f1”< o:p>
f1()< o:p>
f2()< o:p>
environment(f1) <- environment()< o:p>
f1()< o:p>
}< o:p>
> f1()
f1: global< o:p>
> f2()< o:p>
f2: global< o:p>
However if they are called from within a function the results will differ:
> fun()< o:p>
f1: global < o:p>
f2: f1 < o:p>
f1: f1< o:p>
We can see that f1 selects a variable from its lexical scope (global environment) and f2 from calling function fun.
An interesting thing is that function’s f1 lexical scope can be changed by assigning new environment to function f1 within function fun. This forces fun environment into lexical search path of f1 and is another way to simulate one level dynamic scoping.
The second method is useful when a function we want to call is defined externally (for example within a package) and we are unable to change it. The drawback is that called function may stop working because within its internals it might call functions or seek variables that are undefined within changed environment search path – so one has to be cautious with it.
In my next post I plan show an application of this idea on some practical example.
To leave a comment for the author, please follow the link and comment on their blog: R snippets.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.