This should work:
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
Note that finalfun
is a list of closures. The function fnest
takes two functions as inputs and returns a composite function (a closure).
It's now trivial to create a function that operates on your two function lists:
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)
EDIT: In case people are curious about the use of force()
, check out this question on lazy evaluation: Explain a lazy evaluation quirk