范围 - 如果存在具有相同名称的本地var,如何在父环境中评估对象?

Ric*_*rta 10 r environment-variables

如果我有两个使用相同变量名的嵌套环境,我如何获取外部环境的值?

我很难搞清楚实现这个的正确方法.我已经尝试了eval中的一些变体parent.frame(x)sys.frame(x)内部.任何建议,将不胜感激.


例:

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
Run Code Online (Sandbox Code Playgroud)

obj在这种特定情况下,我无法使用明显的解决方案(明确传递.使用不同的变量名称等).


编辑

在下面查看@ GregSnow和@Dwin的答案

  # 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())
Run Code Online (Sandbox Code Playgroud)

关于get()vs 中引用效果的任何想法eval()



42-*_*42- 10

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
Run Code Online (Sandbox Code Playgroud)

也可以用过:eval(quote(obj), envir=sys.frame(-1)).很明显,quote(expr)的含义与"expr"的含义不同.该get函数"期望"(或者可能更准确地设计)来接收字符值,而eval期望调用和表达式,即"语言"对象.R中的数据和语言之间有一种半渗透膜,get是一种膜通道,通过它可以将字符值对象传递到语言域.