R环境和函数调用堆栈 [英] R environments and function call stacks

查看:144
本文介绍了R环境和函数调用堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 get 进行一系列的函数调用,但查找对象名称似乎是跳过环境。例如:

I am trying to use get in series of function calls, but the lookup of the object names seems to skip environments. For example:

foo <- 1 # variable in .GlobalEnv

getter <- function(x) {get(x)}
getter("foo") # returns 1, which is expected

f1 <- function() {
  foo <- 2 # local variable in the function scope
  getter("foo")
}

f1() # still returns 1, would've expected to return 2

为什么调用 f1 返回 foo 在全局环境中,而不是调用函数环境中的 foo

Why is it that calling f1 returns the foo in the global environment and not the foo in the calling function's environment?

如何在调用函数的环境中查找 get ?设置 pos = sys.parent()似乎不起作用。

How do I have get look in the calling function's environment? Setting pos = sys.parent() does not seem to work.

推荐答案

p>如果您定义 getter 来查看父框架,它可以工作:

If you define getter to look in the parent frame, it works:

getter <- function(x) get(x, envir=parent.frame())

然后:

getter("foo")
[1] 1

f1()
[1] 2

这篇关于R环境和函数调用堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆