How to Calculate Cumulative Sums in R with cumsum()
Calculate cumulative sums to track running totals through sequential data — revenue to date, cumulative rainfall, accumulated errors, or year-to-date counts. Each output position holds the total of all elements up to and including that position. If the input vector contains NA, all positions from that point forward will also be NA unless you remove missing values first with na.omit(). For grouped data, pair cumsum() with group_by() so the accumulation resets at each category boundary instead of carrying across groups indiscriminately.
Base R’s cumsum() works directly on vectors:
sales <- c(100, 150, 200, 175, 225)
cumsum(sales)
# [1] 100 250 450 625 850
Add the result as a column with dplyr::mutate(), and use group_by() if you need the cumulative sum to reset within each group boundary:
library(dplyr)
df <- data.frame(
month = c("Jan", "Feb", "Mar", "Apr", "May"),
sales = c(100, 150, 200, 175, 225)
)
df <- df %>% mutate(total_sales = cumsum(sales))
R also provides cumprod(), cummax(), and cummin() for cumulative product, maximum, and minimum. Without group_by(), cumsum() treats all rows as a single sequence regardless of category — always group first when your data has categories.
See also
- cumsum(), Cumulative sum, product, max, min
- dplyr::mutate(), Add new columns