在R中:嵌套两个函数列表并在列表中返回组合函数

时间:2014-04-27 02:45:46

标签: r list function functional-programming nested

我有两个函数列表,我尝试将它们组合成一个函数列表(一个嵌套在另一个函数列表中)。

funlist=list()
funlist[[1]] <- function(x1){2*x1}
funlist[[2]] <- function(x2){3*x2}

anotherlist=list()
anotherlist[[1]]=function(y1){0.5*y1}
anotherlist[[2]]=function(y2){0.7*y2}

列表的长度相同。期望的结果是另一个功能列表:

finalfun=list()
finalfun[[1]] which shall be the same as funlist[[1]](anotherlist[[1]])
...

因此,如果我打电话  finalfun[[1]](6),我会得到结果“6”[2 *(0.5 * 6)],类似于调用:

 funlist[[1]](anotherlist[[1]](6))

我尝试了以下内容来创建一个嵌套两个输入函数的函数:

nestfun <- function(infun,outfun) {lapply(1:length(infun),function(i){outfun[[i]](infun[[i]])})}   
test=nestfun(infun=anotherlist, outfun=funlist)

产生错误:

Error in 2 * x1 : non-numeric argument to binary operator
Called from: lapply(1:length(infun), function(i) {
    outfun[[i]](infun[[i]])
})

我在俯瞰什么?

2 个答案:

答案 0 :(得分:1)

这应该有效:

fnest<-function(f1,f2){  
force(f1)
force(f2)
nest<-function(x) f1(f2(x))}

finalfun<-list()
finalfun<-lapply(1:length(funlist), function (i) fnest(funlist[[i]], anotherlist[[i]]) )

finalfun[[2]](10)
#21

请注意finalfun是一个闭包列表。函数fnest将两个函数作为输入并返回一个复合函数(闭包)。

现在创建一个在两个函数列表上运行的函数是微不足道的:

nestfun<-function(funlist,anotherlist){
fnest<-function(f1,f2){  
force(f1)
force(f2)
nest<-function(x) f1(f2(x))}

finalfun<-list()
finalfun<-lapply(1:length(funlist), function (i) fnest(funlist[[i]], anotherlist[[i]]) ) }

finalfun<-list()
finalfun<-nestfun(funlist,anotherlist)

编辑:如果人们对使用force()感到好奇,请查看有关延迟评估的问题:Explain a lazy evaluation quirk

答案 1 :(得分:1)

这是一种使用功能包中的Compose的方法。注意,由于延迟评估,您需要force参数

library(functional)
Composed <- Map(function(x, y) {
  x <- force(x)
  y <- force(y)
   Compose(y, x)}, 
 funlist,anotherlist)
# A Couple of examples
Composed[[1]](6) 
# [1] 6
Composed[[2]](6)
# [1] 12.6
相关问题