我鼓励你阅读lexical scoping,
但我认为避免编写大量变量的好方法可能是:
get_args_for <- function(fun, env = parent.frame(), inherits = FALSE, ..., dots) {
potential <- names(formals(fun))
if ("..." %in% potential) {
if (missing(dots)) {
# return everything from parent frame
return(as.list(env))
}
else if (!is.list(dots)) {
stop("If provided, 'dots' should be a list.")
}
potential <- setdiff(potential, "...")
}
# get all formal arguments that can be found in parent frame
args <- mget(potential, env, ..., ifnotfound = list(NULL), inherits = inherits)
# remove not found
args <- args[sapply(args, Negate(is.null))]
# return found args and dots
c(args, dots)
}
f_a <- function(b, c = 0, ..., d = 1) {
b <- b + 1
c(b = b, c = c, d = d, ...)
}
f_e <- function() {
b <- 2
c <- 2
arg_list <- get_args_for(f_a, dots = list(5))
do.call(f_a, arg_list)
}
> f_e()
b c d
3 2 1 5
默认设置inherits = FALSE确保我们只从指定的环境中获取变量。
我们还可以在调用get_args_for 时设置dots = NULL,这样我们就不会传递所有变量,
但将省略号留空。
尽管如此,它并不完全健壮,
因为dots 只是简单地附加在末尾,
如果某些参数没有命名,
他们最终可能会按位置匹配。
另外,如果调用中的某些值应该是NULL,
不容易被发现。
我强烈建议不要在 R 包中使用以下这些。
不仅会比较丑,
你会从 R 的 CMD 检查中得到一堆关于未定义全局变量的注释。
其他选项。
f_a <- function() {
return(b + c)
}
f_e <- function() {
b <- 2
c <- 2
# replace f_a's enclosing environment with the current evaluation's environment
environment(f_a) <- environment()
d <- f_a()
d
}
> f_e()
[1] 4
上面的东西可能在 R 包中不起作用,
因为我认为包的功能已锁定其封闭环境。
或者:
f_a <- function() {
with(parent.frame(), {
b + c
})
}
f_e <- function() {
b <- 2
c <- 2
f_a()
}
> f_e()
[1] 4
这样您就不会永久修改其他函数的封闭环境。
但是,这两个函数将共享一个环境,
所以可能会发生这样的事情:
f_a <- function() {
with(parent.frame(), {
b <- b + 1
b + c
})
}
f_e <- function() {
b <- 2
c <- 2
d <- f_a()
c(b,d)
}
> f_e()
[1] 3 5
调用内部函数会修改外部环境中的值。
还有一个更灵活的选择,
因为它只是通过使用eval 临时修改封闭环境。
但是,有些 R 函数会通过“暗魔法”检测它们当前的执行环境,
并且不能被eval所迷惑;
见this discussion。
f_a <- function() {
b <- b + 1
b + c
}
f_e <- function() {
b <- 2
c <- 2
# use current environment as enclosing environment for f_a's evaluation
d <- eval(body(f_a), list(), enclos=environment())
c(b=b, d=d)
}
> f_e()
b d
2 5