简体   繁体   English

使用 purrr 应用累积函数

[英]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 的每个位置,我想计算有多少个数字 > 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

Can you help me do it using purrr.你能帮我用 purrr 来做吗? Can purrr::reduce be used here?这里可以使用 purrr::reduce 吗?

cumsum function can do this cumsum函数可以做到这一点

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

You could use accumulate() from purrr :您可以使用purrr accumulate()

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

It's basically a wrapper around Reduce() with accumulate = TRUE它基本上是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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM