Cumulative sum of a column in R

Cumulative sum of the column in R can be accomplished by using cumsum function. In this tutorial we will see how to

  • Get cumulative sum of column in R
  • Reverse cumulative sum of column in R

Let’s first create the dataframe

df1 = data.frame(State = c('Arizona AZ','Georgia GG', 'Newyork NY','Indiana IN','Florida FL'), Score=c(62,47,55,74,31))
df1

df1 will be

Cumulative sum of column in r 1

 

Get cumulative sum of column in R

Cumulative sum of a column is calculated using cumsum() function as shown below

# cumulative sum

df1$cumulative_score = cumsum(df1$Score) 
df1

resultant dataframe will be

Cumulative sum of column in r 2

 

Get Reverse cumulative sum of column in R

Reverse cumulative sum of a column is calculated using rev() and cumsum() function as shown below

# reverse cumulative sum

df1$rev_cumulative_sum = rev(cumsum(df1$Score))
df1

resultant dataframe will be

Cumulative sum of column in r 3