accumulate()
reduces a vector with a binary function,
keeping all intermediate results, from the initial value to the
final reduced value, i.e. the result you'd have gotten if you used
reduce()
instead of accumulate()
.
accumulate(.x, .f, ..., .init, .dir = c("forward", "backward")) accumulate2(.x, .y, .f, ..., .init)
.x  A list or atomic vector. 

.f  For For 
...  Additional arguments passed on to the mapped function. 
.init  If supplied, will be used as the first value to start
the accumulation, rather than using 
.dir  The direction of reduction as a string, one of

.y  For 
A vector the same length of .x
with the same names as .x
.
If .init
is supplied, the length is extended by 1. If .x
has
names, the initial value is given the name ".init"
, otherwise
the returned vector is kept unnamed.
If .dir
is "forward"
(the default), the first element is the
initial value (.init
if supplied, or the first element of .x
)
and the last element is the final reduced value. In case of a
right accumulation, this order is reversed.
accumulate_right()
is softdeprecated in favour of the .dir
argument as of rlang 0.3.0. Note that the algorithm has
slightly changed: the accumulated value is passed to the right
rather than the left, which is consistent with a right reduction.
reduce()
when you only need the final reduced value.
# With an associative operation, the final value is always the # same, no matter the direction. You'll find it in the last element # for a left accumulation, and in the first element for a right one: 1:5 %>% accumulate(`+`)#> [1] 1 3 6 10 151:5 %>% accumulate(`+`, .dir = "backward")#> [1] 15 14 12 9 5#> [1] 15# It is easier to understand the details of the reduction with # `paste()`. accumulate(letters[1:5], paste, sep = ".")#> [1] "a" "a.b" "a.b.c" "a.b.c.d" "a.b.c.d.e"# Note how the intermediary reduced values are passed to the left # with a left reduction, and to the right otherwise: accumulate(letters[1:5], paste, sep = ".", .dir = "backward")#> [1] "a.b.c.d.e" "b.c.d.e" "c.d.e" "d.e" "e"# `accumulate2()` is a version of `accumulate()` that works with # ternary functions and one additional vector: paste2 < function(x, y, sep = ".") paste(x, y, sep = sep) letters[1:4] %>% accumulate(paste2)#> [1] "a" "a.b" "a.b.c" "a.b.c.d"#> [[1]] #> [1] "a" #> #> [[2]] #> [1] "ab" #> #> [[3]] #> [1] "ab.c" #> #> [[4]] #> [1] "ab.cd" #># Simulating stochastic processes with drift# NOT RUN { library(dplyr) library(ggplot2) rerun(5, rnorm(100)) %>% set_names(paste0("sim", 1:5)) %>% map(~ accumulate(., ~ .05 + .x + .y)) %>% map_dfr(~ data_frame(value = .x, step = 1:100), .id = "simulation") %>% ggplot(aes(x = step, y = value)) + geom_line(aes(color = simulation)) + ggtitle("Simulations of a random walk with drift") # }