Tarak Tarak - 1 year ago 114
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

Answer Source

We can use cumsum

   mutate(runningTotal = cumsum(cost))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download