【问题标题】:R cumsum with multiplication based on valueR cumsum 与基于值的乘法
【发布时间】:2017-09-28 01:02:30
【问题描述】:

我有一个正数向量,这样 - 如果数字大于或等于 1,则添加 - 如果数字小于 1,则乘以累积和。

例如

> set.seed(0)
> x <- sample(c(0.9, 0.9, 0.9, 1:3), 10, replace=T)
> x
 [1] 3.0 0.9 0.9 1.0 3.0 0.9 3.0 3.0 1.0 1.0

结果向量

3  2.7  2.43  3.43  6.43  5.787  8.787  11.787  12.787  13.787

有没有办法在不使用 for 循环的情况下做到这一点?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这是@G.Grothendieck 使用purrr::accumulate 的答案的tidyverse 替代方案:

    library(tidyverse)
    accumulate(x, function(x, y) if_else(y < 1, x * y, x + y))
    #>  [1]  3.000  2.700  2.430  3.430  6.430  5.787  8.787 11.787 12.787 13.787
    

    【讨论】:

      【解决方案2】:

      这里有一些只使用基本 R 的替代方案:

      1) 减少

      sumprod <- function(x, y) if (y < 1) x * y else x + y
      Reduce(sumprod, x, acc = TRUE)
      ## [1]  3.000  2.700  2.430  3.430  6.430  5.787  8.787 11.787 12.787 13.787
      

      2) 递归

      cumsumprod_ <- function(x, init) {
            if (length(x)) c(init, Recall(x[-1], sumprod(tail(init, 1), x[1])))
            else init
      }
      cumsumprod <- function(x) {
            if (length(x) < 2) x
            else cumsumprod_(x[-1], x[1])
      }
      
      cumsumprod(x)
      ## [1]  3.000  2.700  2.430  3.430  6.430  5.787  8.787 11.787 12.787 13.787
      

      更新:修复了 (2) 中的边缘情况。

      【讨论】:

        猜你喜欢
        • 2017-10-16
        • 2021-02-21
        • 2018-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        相关资源
        最近更新 更多