Search code examples
rsum

R, New Column that's a Sum to Row


I'm trying to find an easy way to create a new variable that will give me the sum of a column, up to a certain row. I input a new variable, "Spend.to.Date" to illustrate what I'm looking for. I can do it "by hand" by specifying the specific cells to add together, but I'd imagine there must be a more efficient way to achieve it. Any help would be greatly appreciated!

df <- as.data.frame(matrix(c(1, 2, 3, 4, 5, 100, 200, 300, 400, 500), 5, 2)) #Take as given

colnames(df) <- c("Day", "Spend")

df$Spend.to.Date <- c(100, 300, 600, 1000, 1500)

Solution

  • df$Spend.to.Date <- cumsum(df$Spend)