使用purrr应用累积函数

Bra*_*ani 2 r purrr

对于x的每个位置,我想计算多少个数> 5.这是我的代码,使用for循环:

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
Run Code Online (Sandbox Code Playgroud)

你能帮我用purrr做吗?可以在这里使用purrr :: reduce吗?

use*_*721 6

cumsum 功能可以做到这一点

cumsum(x>5)
#[1] 0 1 1 2 3 4 5 5 5 5
Run Code Online (Sandbox Code Playgroud)

  • @amarchin我添加了一个使用`base R`的方法,因为我相信没有人在使用base函数完成时添加一个包,除非它给出了巨大的好处. (2认同)

Ste*_*pré 6

你可以使用accumulate()来自purrr:

accumulate(x > 5, `+`)
#[1] 0 1 1 2 3 4 5 5 5 5
Run Code Online (Sandbox Code Playgroud)

这基本上是一个包装周围Reduce()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)
}
Run Code Online (Sandbox Code Playgroud)