Tarak Tarak - 2 months ago 18
R Question

R - aggregating sum row wise

I have a data frame mydf as

mydf <- data.frame(month = c('apr', 'may', 'june'),cost = c(100, 150, 200))


I wish to get a runningTotal that sums each record cumulatively

month cost runningTotal
1 apr 100 100
2 may 150 250
3 june 200 450


I tried using dplyr sum but didn't work.
Can someone help me find the most efficient way of doing this
Thanks.

Answer

We can use cumsum

library(dplyr)
mydf%>%
   mutate(runningTotal = cumsum(cost))
Comments