cumsum()

cumsum(x)
Returns: numeric · Updated March 13, 2026 · Base Functions
cumulative vectors math cumsum base

The cumsum() function computes the cumulative sum of a vector, returning a vector of the same length where each element is the sum of all preceding elements. It is one of the simplest ways to build running totals in reporting, finance, and time-series analysis.

Syntax

cumsum(x)

Parameters

ParameterTypeDefaultDescription
xnumericrequiredA numeric vector

Examples

Basic usage

x <- c(1, 2, 3, 4, 5)

cumsum(x)
# [1]  1  3  6 10 15

Tracking totals

# Running total revenue
sales <- c(100, 150, 80, 200, 175)

cumsum(sales)
# [1] 100 250 330 530 705

Common Patterns

Financial calculations

# Cumulative returns
prices <- c(100, 102, 98, 105, 110)
cumsum(diff(prices))
# [1]   2  -4   7   5

# Running profit/loss
transactions <- c(100, -50, 200, -30, 50)
cumsum(transactions)
# [1] 100  50 250 220 270

Sequence generation

# Arithmetic progression via cumsum
cumsum(rep(1, 10))
# [1]  1  2  3  4  5  6  7  8  9 10

# Triangular numbers
cumsum(1:10)
# [1]  1  3  6 10 15 21 28 36 45 55

See Also