如何撰写功能清单

Cat*_*331 5 r

例如,我有一个向量函数:fun_vec <- c(step1,step2,step3)。现在,我要像这样组成它们:step1(step2(step3(x)))。我该如何使用fun_vec?(假设它fun_vec不是固定的,可以具有更多或更少的功能。)

r2e*_*ans 5

与Frank的用法类似freduce,您可以使用Reduce

step1 <- function(a) a^2
step2 <- function(a) sum(a)
step3 <- function(a) sqrt(a)
steps <- list(step1, step2, step3)
Reduce(function(a,f) f(a), steps, 1:3)
# [1] 3.741657
step3(step2(step1(1:3)))
# [1] 3.741657
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式看到它的“作用”:

Reduce(function(a,f) f(a), steps, 1:3, accumulate=TRUE)
# [[1]]
# [1] 1 2 3
# [[2]]
# [1] 1 4 9
# [[3]]
# [1] 14
# [[4]]
# [1] 3.741657
Run Code Online (Sandbox Code Playgroud)


Art*_*lov 2

看一眼purrr::compose。如果您的函数存储在列表中,请使用purrr::invoke将该列表传递给compose

fun_vec <- c( exp, log10, sqrt )
f <- purrr::invoke( purrr::compose, fun_vec )
f(4)                      # 1.35125
exp( log10( sqrt(4) ) )   # 1.35125
Run Code Online (Sandbox Code Playgroud)