Brani
Brani

Reputation: 6784

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?

Upvotes: 2

Views: 794

Answers (2)

Steven Beaupr&#233;
Steven Beaupr&#233;

Reputation: 21621

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)
}

Upvotes: 7

user2100721
user2100721

Reputation: 3587

cumsum function can do this

cumsum(x>5)
#[1] 0 1 1 2 3 4 5 5 5 5

Upvotes: 7

Related Questions