我有一个功能列表
functions <- list(f1, f2, f3, ...)
Run Code Online (Sandbox Code Playgroud)
我需要x通过所有函数传递一个对象.我可以这样做:
for (fun in functions){
fun(x)
}
Run Code Online (Sandbox Code Playgroud)
函数不返回任何内容,但它们的顺序很重要,即f1(x)必须先应用f2(x).
因此,我正在考虑使用lapply:
lapply(functions, function(fun) fun(x))
Run Code Online (Sandbox Code Playgroud)
但我不知道是否lapply首先应用列表的第一个函数functions或者它是否遵循另一个订单.通过循环,我保证订购,但它可能会变慢.
任何的想法?
问题“pass x through ...”的措辞表明您认为这将完成“组合”,即对先前应用程序的结果进行函数的串行应用。尽管您可以重新设计for循环来做到这一点,但您提出的解决方案都不会做到这一点。看一下?funprog帮助页面,我无耻地引用了部分内容:
## Iterative function application:
Funcall <- function(f, ...) f(...)
## Compute log(exp(acos(cos(0))
Reduce(Funcall, list(log, exp, acos, cos), 0, right = TRUE)
Run Code Online (Sandbox Code Playgroud)
将循环版本的结果for与实际Reduce版本进行比较:
> flist <- list(log, exp, acos, cos)
> arg <- 0; for (f in flist) {arg <- f(arg)}
> arg
[1] 6.123234e-17
> Funcall <- function(f, ...) f(...)
> ## Compute log(exp(acos(cos(0))
> Reduce(Funcall, list(log, exp, acos, cos), 0, right = TRUE)
[1] 0
Run Code Online (Sandbox Code Playgroud)
这表明这<something>确实正在发生:
arg <- 0; for (f in flist) {arg <- f(arg);cat(arg,"\n")}
-Inf
0
1.570796
6.123234e-17
Run Code Online (Sandbox Code Playgroud)
但它们并不相同,因为right=TRUE实际上颠倒了应用顺序并解释了最终结果中的细微差异。比较:
arg <- 0; for (f in rev(flist)) {arg <- f(arg);cat(arg,"\n")}
Run Code Online (Sandbox Code Playgroud)