Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acumulative sum in R

Tags:

r

cumsum

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?

like image 873
Manuel Rodríguez Avatar asked Dec 18 '25 10:12

Manuel Rodríguez


2 Answers

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
like image 61
KU99 Avatar answered Dec 20 '25 22:12

KU99


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))
like image 35
akrun Avatar answered Dec 21 '25 00:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!