If I have two nested environments using the same variable name, how would I grab the value of the outer environment?
I am having difficulty figuring out the correct way to implement this. I have tried a few variations of parent.frame(x) and sys.frame(x) inside eval. Any suggestions would be appreciated.
EXAMPLE:
outerFunc <- function() {
obj <- "Outer Object"
innerFunc()
}
innerFunc <- function() {
# A local variable with same name is created
obj <- "Inner Object"
# would like to grab the value of obj from the outer environment
obj.callingFunc <- eval(obj, envir=sys.frame(-1))
cat(obj.callingFunc) # gives "Inner Object" instead of "Outer Object"
}
> outerFunc()
Inner Object
The obvious solutions (Pass obj explicitly. Use a different variable name, etc) are not available to me in this specific case.
EDIT
examining @GregSnow’s and @Dwin’s answers below
# THESE WORK
eval(quote(obj), envir=parent.frame()) # equivalent to evalq(obj, envir=parent.frame())
get("obj", envir=parent.frame())
# THESE DO *NOT* WORK
eval("obj", envir=parent.frame())
get(quote(obj), envir=parent.frame())
Any thoughts as to the effects of quoting in get() vs eval()?
Could have also used:
eval(quote(obj), envir=sys.frame(-1)). It becomes clear that the meaning of quote(expr) is different than than of “expr”. Thegetfunction is “expecting” (or perhaps more accurately is designed) to receive character values, whereasevalis expecting calls and expressions, i.e “language” objects. There is sort of a semi-permeable membrane between data and language in R andgetis one of the membrane channels through which you can pass character valued objects to language domain.