Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope -- how to evaluate an object in parent environment if local var with same name exists?

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()?



like image 775
Ricardo Saporta Avatar asked Nov 30 '12 20:11

Ricardo Saporta


1 Answers

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
  cat( get('obj', envir=parent.frame()) )

   } 

 outerFunc()
#Outer Object

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". The get function is "expecting" (or perhaps more accurately is designed) to receive character values, whereas eval is expecting calls and expressions, i.e "language" objects. There is sort of a semi-permeable membrane between data and language in R and get is one of the membrane channels through which you can pass character valued objects to language domain.

like image 184
IRTFM Avatar answered Oct 22 '22 09:10

IRTFM