R中的函数组成(以及高级函数)

时间:2021-09-18 22:03:55

Is there something like a function composition in R?

在R中有像函数合成这样的东西吗?

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

我认为在haskell中它是“(.)”,在agda中它是环操作符。

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

此外,我在r中找到了关于高级函数编程的litte信息,我发现了函数“Reduce”、“Map”、“Filter”……,有更多的吗?指针吗?

2 个解决方案

#1


8  

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...).

关于第二点,有很多这样的;我认为最常用的是*apply family (sapply、mapply、tapply、lapply、apply…)。

#2


16  

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.)

(注意,函数是从左到右应用的。)

#1


8  

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...).

关于第二点,有很多这样的;我认为最常用的是*apply family (sapply、mapply、tapply、lapply、apply…)。

#2


16  

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.)

(注意,函数是从左到右应用的。)