Home > Enterprise >  Cumulative sum in the decreasing order in R
Cumulative sum in the decreasing order in R

Time:08-18

I have a data table below.

Idle_min <- c(1, 2, 3, 5, 6, 8)
Freq <- c(16, 11, 5, 7, 3, 1)

df <- data.frame(Idle_min, Freq)

I want to obtain the cumulative frequency and add it as a new column, but it should be in descending order. That means, the first row should represent the total of Freq, then the second row represents Total-16, and so on.

So the output I expected for the dummy data above should look like this.

Idle_min Freq cumulative
1 16 43
2 11 27(43-16)
3 5 16 (27-11)
5 7 11 (16-5)
6 3 4 (11-7)
8 1 1 (4-3)

How did I suppose to obtain the cumulative in the decreasing order?

CodePudding user response:

We can use reverse on the column before doing the cumsum

df$cumulative <-  with(df, rev(cumsum(rev(Freq))))

-output

> df
  Idle_min Freq cumulative
1        1   16         43
2        2   11         27
3        3    5         16
4        5    7         11
5        6    3          4
6        8    1          1
  • Related