cumulative sum elements

Viewed 92

I have:

id num
1 5
2 2
3 10
4 20
5 3

and I want to get:

id num
1 40
2 35
3 33
4 23
5 3

so: 1 or more, 2 or more ...

3 Answers

In base R you could do this: The logic was first implemented by akrun:

df[, 2] <- rev(cumsum(rev(df[, 2])))

Output:

  id num
1  1  40
2  2  35
3  3  33
4  4  23
5  5   3

Or another option would be:

library(purrr)

df1 %>%
  mutate(num = accumulate(num, `+`, .dir = "backward"))

  id num
1  1  40
2  2  35
3  3  33
4  4  23
5  5   3

We can do

library(dplyr)
df1 %>%
    mutate(num = rev(cumsum(rev(num))))

-ouptut

id num
1  1  40
2  2  35
3  3  33
4  4  23
5  5   3

Or use

library(spatstat.utils)
df1 %>%
    mutate(num = revcumsum(num))
  id num
1  1  40
2  2  35
3  3  33
4  4  23
5  5   3

data

df1 <- structure(list(id = 1:5, num = c(5L, 2L, 10L, 20L, 3L)), 
class = "data.frame", row.names = c(NA, 
-5L))
Related