用 purrr::reduce() 迭代

Iteration with purrr::reduce()

给定一个初始值为 a = 3 的函数 f(a, x) = a*x,假设有一个迭代,其中 a 在下一步中被赋值为 f(a, x)

如何使用purrr实现迭代?下面说的不太对

library(purrr)
a <- 3
f <- function(a, x) a*x

2:4 %>% reduce(~f(a, .))
#> [1] 18

2:4 %>% accumulate(~f(a, .))
#> [1]  2  6 18

reprex package (v0.3.0)

于 2020-04-24 创建

你似乎在追求

2:4 %>% accumulate(~f(.y, .x), .init=3)
# [1]  3  6 18 72

.x 值表示您之前的值,这里的 .y 是您输入的向量中的下一个元素。与其在函数中硬编码 a=3,不如我们通过 .init= 将其传递给它仅在第一次迭代时发生。

在基础 R 中,您可以将 Reduceaccumulate = TRUE 一起使用。

Reduce(f, 2:4, init = 3, accumulate = TRUE)
#[1]  3  6 18 72