Brani Brani - 1 month ago 9
R Question

Using purrr to apply cumulative function

For each position of x, I want to count how many numbers were > 5.
Here is my code, using for loop:

x<-c(2,8,4,9,10,6,7,3,1,5)

y <- vector()
for (i in seq_along(x)) {
x1 <- x[1:i]
y <- c(y, length(x1[x1>5]))
}
> y
[1] 0 1 1 2 3 4 5 5 5 5


Can you help me do it using purrr. Can purrr::reduce be used here?

Answer

You could use accumulate() from purrr:

accumulate(x > 5, `+`)
#[1] 0 1 1 2 3 4 5 5 5 5

It's basically a wrapper around Reduce() with accumulate = TRUE

accumulate <- function(.x, .f, ..., .init) {
  .f <- as_function(.f, ...)

  f <- function(x, y) {
    .f(x, y, ...)
  }

  Reduce(f, .x, init = .init, accumulate = TRUE)
}