What is the cumsum() function in R?

Overview

The cumsum() function in R computes the cumulative sum of elements in a vector object.

Syntax

cumsum(x)
The syntax for the cumsum() function

Parameter value

The cumsum() function takes a single parameter value, x, which represents a numeric or complex object.

Return value

The cumsum() function returns a vector of the same length as x.

Example

# implementing the cumsum() function to take the sum of elements in the vector objecs
cumsum(1:10)
cumsum(c(2, 3, 1, -4, 2))

Explanation

  • Line 2: We obtain the cumulative sum of numbers starting from 1 to 10 using the cumsum() function.
  • Line 3: We obtain the cumulative sum of random numbers of a vector object using the cumsum() function.

Free Resources