Acumulative sum in R

Viewed 64

I have data containing columns x and lx, I want to get cumulative sum on lx basis. My data is like:

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

and I want to get output like :

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

ie. accumulative sum

So it there a possible way to achieve it?

3 Answers

We can reverse the column, get the cumulative sum (cumsum) and reverse the output

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

-output

#  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

Or another option is revcumsum

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

Or using accumulate from purrr

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

data

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

You could also do:

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

You can try cumsum like below

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

which gives

   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
Related