【问题标题】:Using purrr to apply cumulative function使用 purrr 应用累积函数
【发布时间】:2016-10-22 06:13:39
【问题描述】:

对于 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

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

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    您可以使用purrr 中的accumulate()

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

    它基本上是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)
    }
    

    【讨论】:

      【解决方案2】:

      cumsum 函数可以做到这一点

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

      【讨论】:

      • @Brani 要求使用 purrr 函数的解决方案。
      • @amarchin 我添加了一种使用base R 的方法,因为我相信没有人可以在可以使用基本函数完成时添加一个包,除非它可以带来巨大的好处。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多