# cumsum() Function In R: Sum of a Numeric Object’s Cumulative Value

It is highly typical in many data analytics to compute the cumulative sum of your variables of interest.

The cumsum() function in the R programming language makes it simple to compute the cumulative sum.

## What is the cumsum() function in R?

The cumulative sum is the sum of a collection of numbers whose sum value increases as the sequence of numbers increases.

The cumsum() function is used to compute the cumulative sum of the vector supplied as an input. We can read the syntax of this function below.

Syntax:

cumsum(x)

Parameters:

• x: The numeric

## How to use the cumsum() function in R?

### Using the cumsum() function with a vector

In this example, we will use the cumsum() function in R with a vector. So, we need to create a vector as follows:

# Create the vector
x <- 10:15
y <- -10:-5

# View the vectors
x
y

Output

[1] 10 11 12 13 14 15
[1] -10  -9  -8  -7  -6  -5

Now, we will apply the cumsum() function to these vectors.

# Create the vector
x <- 10:15
y <- -10:-5

# Using the cumsum() function
cat("Using the cumsum() function for vector x:", cumsum(x), "\n")
cat("Using the cumsum() function for vector y:", cumsum(y))

Output

Using the cumsum() function for vector x: 10 21 33 46 60 75
Using the cumsum() function for vector y: -10 -19 -27 -34 -40 -45

For another example, we will apply this function with a float number.

# Create the vector
x <- c(2.2, 6.3, 4.6, 2.3)
y <- c(2.1, 2.6, 3.5, 9.1)

# Using the cumsum() function
cat("Using the cumsum() function for vector x:", cumsum(x), "\n")
cat("Using the cumsum() function for vector y:", cumsum(y))

Output

Using the cumsum() function for vector x: 2.2 8.5 13.1 15.4
Using the cumsum() function for vector y: 2.1 4.7 8.2 17.3

### Using the cumsum() function to plot

We can use the plot() function to visualize the cumsum() function’s graph. The output of the cumulative sum can be neatly visualized using the plot() function. Let’s use the vector below as our data.

# Create the data
data <- c(10, 12, 16, 18, 20, 25)

The cumsum() function in R can be used to determine the vector’s cumulative sum.

# Create the data
data <- c(10, 12, 16, 18, 20, 25)

# Using cumsum() function
res <- cumsum(data)
res

Output

[1]  10  22  38  56  76 101

Now we will use the results below to plot the graph.

# Create the data
data <- c(10, 12, 16, 18, 20, 25)

# Using cumsum() function
res <- cumsum(data)

# Plot
plot(
x = seq_len(length(res)),
y = res, col = "red",
xlab = "Size of the Example Vector", ylab = "Cumulative Sum",
main = "Cumulative Analysis"
)

rect(0, 55, 10, 0, col = "grey92", border = "black", )

points(
x = seq_len(length(res)), y = res,
type = "l", col = "#1b98e0"
)

points(
x = seq_len(length(res)), y = res,
pch = 16, col = "#1b98e0"
)

Output