R 中分配给 %@% 运算符的函数组合
Function composition assigned to %@% operator in R
在数学中,我们经常使用函数的叠加。显然,我们可以定义任意数量函数的叠加,例如 (h∘g∘f)(x)(h∘g∘f)(x)。我的问题如下 -> How to define a superposition binary operator %@% ?
让我们从一个简单的例子开始。
sin %@% -pi/4
上面的表达式returns取值sin(−π/4)
评估时。我想获得 %@% 运算符的实现,它允许叠加任何有限数量的函数,如下例所示(请参见下文)。你能给我提供没有任何额外 R 包的解决方案吗?会有很大帮助。
tanh %@% exp %@% abs %@% sin %@% -pi/4
以下函数将 this answer 中的代码改编为类似的问题。
`%@%` <- function(f, g) {
if(is.function(g))
function(...) f(g(...))
else f(g)
}
sin %@% (-pi/4)
#[1] -0.7071068
(sin %@% cos)(-pi/4)
#[1] 0.6496369
匿名函数必须放在方括号{.}
.
之间
pow2 <- function(x) x^2
(pow2 %@% sin)(-pi/4)
#[1] 0.5
({function(x) x^2} %@% sin)(-pi/4)
#[1] 0.5
我不知道是否合适,但我的初衷是:
`%@%` <- function(f,g) {
if(is.function(f) && is.function(g)) {
#both functions, composition as usual
return(function(...) {f(g(...))} )
}
if(!is.function(f)) {
#f is no function, hence a constant value, return it.
return(f)
}
if(is.function(f) && !is.function(g)) {
#f is function, g not, hence g is the argumemnt to f
return(f(g))
}
}
一些测试:
sq <- function(x) x^2
sq %@% sq %@% 5 #625
base::identity %@% base::identity %@% 5 #5
exp %@% log %@% 5 #5
5 %@% sin #5
tanh %@% exp %@% abs %@% sin %@% -pi/4 #0.1903985
在数学中,我们经常使用函数的叠加。显然,我们可以定义任意数量函数的叠加,例如 (h∘g∘f)(x)(h∘g∘f)(x)。我的问题如下 -> How to define a superposition binary operator %@% ?
让我们从一个简单的例子开始。
sin %@% -pi/4
上面的表达式returns取值sin(−π/4) 评估时。我想获得 %@% 运算符的实现,它允许叠加任何有限数量的函数,如下例所示(请参见下文)。你能给我提供没有任何额外 R 包的解决方案吗?会有很大帮助。
tanh %@% exp %@% abs %@% sin %@% -pi/4
以下函数将 this answer 中的代码改编为类似的问题。
`%@%` <- function(f, g) {
if(is.function(g))
function(...) f(g(...))
else f(g)
}
sin %@% (-pi/4)
#[1] -0.7071068
(sin %@% cos)(-pi/4)
#[1] 0.6496369
匿名函数必须放在方括号{.}
.
pow2 <- function(x) x^2
(pow2 %@% sin)(-pi/4)
#[1] 0.5
({function(x) x^2} %@% sin)(-pi/4)
#[1] 0.5
我不知道是否合适,但我的初衷是:
`%@%` <- function(f,g) {
if(is.function(f) && is.function(g)) {
#both functions, composition as usual
return(function(...) {f(g(...))} )
}
if(!is.function(f)) {
#f is no function, hence a constant value, return it.
return(f)
}
if(is.function(f) && !is.function(g)) {
#f is function, g not, hence g is the argumemnt to f
return(f(g))
}
}
一些测试:
sq <- function(x) x^2
sq %@% sq %@% 5 #625
base::identity %@% base::identity %@% 5 #5
exp %@% log %@% 5 #5
5 %@% sin #5
tanh %@% exp %@% abs %@% sin %@% -pi/4 #0.1903985