accumulate
From purrr v0.2.2.2
by Lionel Henry
Accumulate recursive folds across a list
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.
Usage
accumulate(.x, .f, ..., .init)accumulate_right(.x, .f, ..., .init)
Arguments
- .x
A list or atomic vector.
- .f
A two-argument function.
- ...
Additional arguments passed on to
.f
.- .init
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 thatreduce
returns the correct value when.x
isis_empty()
.
Examples
# NOT RUN {
1:3 %>% accumulate(`+`)
1:10 %>% accumulate_right(`*`)
# From Haskell's scanl documentation
1:10 %>% accumulate(max, .init = 5)
# 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_df(~ 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")
# }
Community examples
Looks like there are no examples yet.