【发布时间】:2016-04-20 20:50:12
【问题描述】:
我真的找遍了整个地方,但没有找到我的问题的答案:
广义问题:
- 如何在不启动 R 函数的情况下评估参数 (
formals())? - 尽管 R 有“惰性评估”,您如何评估 R 中的整个环境?
我的问题:
我想获取 R 中任何函数的参数的计算时间。例如,让我们考虑一个函数:
foo <- function(x, arg1 = 2, arg2 = arg3[1], arg3 = rnorm(10^6)) {
rnorm(10^7) # whatever time-consuming computation here
arg3^2
message("Too bad you had to launch the whole function !")
}
你会注意到困难:
- 有些参数是必需的 (
x),有些不是。 [结果:使用formals()将不会返回未计算的 x 表达式!] - 一些参数是在另一个参数的函数中计算的,在它之后定义(
arg2是用arg3计算的)
想要的输出:
> system.time(foo(x=1))
Too bad you had to launch the whole function !
user system elapsed
1.835 0.000 1.573
> solution.function(foo, list(x=1))
The answer is in reality much lower ! It takes only 0.2 sec to compute the arguments !
【问题讨论】:
标签: r functional-programming arguments lazy-evaluation