Reputation: 359
Given a function f(a, x) = a*x
with an initial a = 3
, suppose to have an iteration where a
is assigned with f(a, x)
in the next step.
x = 2
, a
is assigned with f(3, x = 2) = 6
, then; x = 3
, a
is assigned with f(6, x = 3) = 18
, then; x = 4
, a
is assigned with f(18, x = 4) = 72
;How to use purrr
to realize the iteration? The following is not quite right.
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
Created on 2020-04-24 by the reprex package (v0.3.0)
Upvotes: 2
Views: 626
Reputation: 388817
In base R, you can use Reduce
with accumulate = TRUE
.
Reduce(f, 2:4, init = 3, accumulate = TRUE)
#[1] 3 6 18 72
Upvotes: 2
Reputation: 206167
Here you seem to be after
2:4 %>% accumulate(~f(.y, .x), .init=3)
# [1] 3 6 18 72
The .x
value represents your previous value and the .y
here is the next elements from the vector you are piping in. Rather than hard coding the a=3
in the function, we pass that in via .init=
to it only occurs on the first iteration.
Upvotes: 1