【问题标题】:Acumulative sum in RR中的累积和
【发布时间】:2021-05-12 20:50:20
【问题描述】:

我有包含列 x 和 lx 的数据,我想在 lx 的基础上获得累积总和。我的数据是这样的:

x l(x)
20 100.000
21 99.644
22 99.286
23 98.925
24 98.561
25 98.195
26 97.829

我想得到如下输出:

x l(x)
20 692.440
21 592.440
22 492.796
23 393.510
24 294.585
25 196.024
26 97.829

即。累计

那么有没有办法实现呢?

【问题讨论】:

    标签: r cumsum


    【解决方案1】:

    我们可以reverse 列,得到累积和(cumsum)和reverse 输出

    df$`l(x)` <- with(df, rev(cumsum(rev(`l(x)`))))
    

    -输出

    #  x    l(x)
    #1 20 692.440
    #2 21 592.440
    #3 22 492.796
    #4 23 393.510
    #5 24 294.585
    #6 25 196.024
    #7 26  97.829
    

    或者另一个选项是revcumsum

    library(spatstat.utils)
    df$`l(x)` <- revcumsum(df$`l(x)`)
    

    或者使用来自purrr的accumulate

    library(purrr)
    library(dplyr)
    df %>%
         mutate(`l(x)` = accumulate(`l(x)`, `+`, .dir = 'backward'))
    

    数据

    df <- structure(list(x = 20:26, `l(x)` = c(100, 99.644, 99.286, 98.925, 
    98.561, 98.195, 97.829)), class = "data.frame", row.names = c(NA, 
    -7L))
    

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      df[, 2] <- Reduce("+", df[, 2], accumulate = TRUE, right = TRUE)
      
         x    l(x)
      1 20 692.440
      2 21 592.440
      3 22 492.796
      4 23 393.510
      5 24 294.585
      6 25 196.024
      7 26  97.829
      

      【讨论】:

        【解决方案3】:

        您可以尝试cumsum,如下所示

        transform(
          df,
          `l(x)` = sum(`l(x)`) - cumsum(c(0, head(`l(x)`, -1)))
        )
        

        给了

           x    l.x.
        1 20 692.440
        2 21 592.440
        3 22 492.796
        4 23 393.510
        5 24 294.585
        6 25 196.024
        7 26  97.829
        

        【讨论】:

          猜你喜欢
          • 2021-06-13
          • 2013-05-20
          • 2020-08-31
          • 1970-01-01
          • 2014-09-29
          • 1970-01-01
          • 1970-01-01
          • 2022-12-05
          • 2014-06-21
          相关资源
          最近更新 更多