
accumulate
applies a function recursively over a list from the left, while
accumulate_right
applies the function from the right. Unlike reduce
both functions keep the intermediate results.
accumulate(.x, .f, ..., .init)accumulate_right(.x, .f, ..., .init)
A list or atomic vector.
For reduce()
, a 2-argument function. The function will be
passed the accumulated value as the first argument and the "next" value
as the second argument.
For reduce2()
, a 3-argument function. The function will be passed the
accumulated value as the first argument, the next value of .x
as the
second argument, and the next value of .y
as the third argument.
Additional arguments passed on to .f
.
If supplied, will be used as the first value to start
the accumulation, rather than using x[[1]]
. This is useful if
you want to ensure that reduce
returns a correct value when .x
is empty. If missing, and x
is empty, will throw an error.
# NOT RUN {
1:3 %>% accumulate(`+`)
1:10 %>% accumulate_right(`*`)
# From Haskell's scanl documentation
1:10 %>% accumulate(max, .init = 5)
# Understanding the arguments .x and .y when .f
# is a lambda function
# .x is the accumulating value
1:10 %>% accumulate(~ .x)
# .y is element in the list
1:10 %>% accumulate(~ .y)
# 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")
# }
Run the code above in your browser using DataLab