Function Composition in R (and high level functions)

喜夏-厌秋 提交于 2020-01-01 08:03:57

问题


Is there something like a function composition in R?

I think in haskell it's somthing like "(.)" and in agda it's the ring operator.

Also, I find litte information on high level functional programming in R. I found the Functions "Reduce", "Map", "Filter"..., are there more? Any pointers?


回答1:


You may make compositing function like this:

composite<-function(f,g) function(...) f(g(...))

f<-function(x) x+1;
g<-function(x) x*2;
composite(f,g)(7)
composite(g,f)(7)

or make operator of this.

About the second point, there are lots of such; I think the most used are the *apply family (sapply, mapply, tapply, lapply, apply...).




回答2:


The functional package has a Compose functional which generalizes to any number of functions:

set.seed(123)
x <- matrix(runif(100), 10, 10)
mean(rowSums(scale(x)))
# [1] 5.486063e-18

library(functional)
Compose(scale, rowSums, mean)(x)
# [1] 5.486063e-18

(Note that the functions are applied from left to right.)



来源:https://stackoverflow.com/questions/4918819/function-composition-in-r-and-high-level-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!