匿名将变量从当前环境传递到子函数调用

时间:2013-09-18 18:54:11

标签: r eval environment

下面定义的函数testfun1执行我想要的操作。 (有关所有这些的原因,请参阅代码示例下方的背景信息。)我想问你的问题是我在testfun2中尝试的原因不起作用。对我来说,两者似乎都在做同样的事情。正如testfun2中的print所示,testfun2内的辅助函数的评估发生在正确的环境中,但是来自main函数环境的变量被神奇地传递给{{1中的辅助函数},但不在testfun1。你们有谁知道为什么吗?

testfun2

背景信息:我有一个很大的R代码,我想在main函数中调用helperfunctions。它们改变了主要功能环境的变量。所有这一切的目的主要是为了整理我的代码。 (主要功能代码目前超过2000行,多次调用各种辅助功能,其长度为40-150行......)
请注意,我的辅助函数的参数数量非常多,因此传统的函数参数显式传递(“helpfun <- function(){ x <- x^2 + y^2 } testfun1 <- function(x,y){ xy <- x*y environment(helpfun) <- sys.frame(sys.nframe()) x <- eval(as.call(c(as.symbol("helpfun")))) return(list(x=x,xy=xy)) } testfun1(x = 2,y = 1:3) ## works as intended eval.here <- function(fun){ environment(fun) <- parent.frame() print(environment(fun)) eval(as.call(c(as.symbol(fun)))) } testfun2 <- function(x,y){ print(sys.frame(sys.nframe())) xy <- x*y x <- eval.here("helpfun") return(list(x=x,xy=xy)) } testfun2(x = 2,y = 1:3) ## helpfun can't find variable 'x' despite having the same environment as in testfun1... ”)会很麻烦,并且不会产生我所瞄准的代码的整理。因此,我需要匿名地将变量从父框架传递给辅助函数。

1 个答案:

答案 0 :(得分:2)

请改用:

eval.here <- function(fun){
 fun <- get(fun)
 environment(fun) <- parent.frame()
 print(environment(fun))
 fun()
}

结果:

> testfun2(x = 2,y = 1:3)

<environment: 0x0000000013da47a8>
<environment: 0x0000000013da47a8>
$x
[1]  5  8 13

$xy
[1] 2 4 6
相关问题