R中的累计和

Acumulative sum in R

我有包含列 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

即。累计金额

那么有什么方法可以实现吗?

我们可以rev删除该列,得到累计和(cumsum)并rev删除输出

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))

您还可以这样做:

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

您可以像下面那样尝试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