I am trying to calculate the cumulative sum for each row using the following code:
df <- data.frame(count=1:10) for (loop in (1:nrow(df))) {df[loop,"acc_sum"] <- sum(df[1:loop,"count"])}
But I don't like the explicit loop here, how can I modify it?
The definition of the cumulative sum is the sum of a given sequence that is increasing or getting bigger with more additions. The real example of a cumulative sum is the increasing amount of water in a swing pool. Example: Input: 10, 15, 20, 25, 30. Output: 10, 25, 45, 70, 100.
You want cumsum()
df <- within(df, acc_sum <- cumsum(count))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With