Calculate Cumulative Sum of a Numeric Object – cumsum() Function

cumsum() Functionin detail

The cumulative sum is the running total of a sequence of numbers, where each value in the output is the sum of all previous values including the current one.

cumsum() Function in R

The cumsum() function in R is used to compute the cumulative sum of a numeric vector.

Syntax:

cumsum(x)

Parameters:

  • x: A numeric vector

Example 1: Using cumsum() with a Sequence of Numbers

# R program to demonstrate cumsum() function

# Applying cumsum() on sequences
cumsum(2:5)
cumsum(-3:-7)

Output:

[1]  2  5  9 14
[1]  -3  -7 -12 -18 -25

Example 2: Using cumsum() with Custom Vectors

# Defining numeric vectors
vec1 <- c(3, 6, 8, 10)
vec2 <- c(1.2, 4.5, 7.3)

# Calculating cumulative sum
cumsum(vec1)
cumsum(vec2)

Output:

[1]  3  9 17 27
[1]  1.2  5.7 13.0

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *