Search code examples
rsumrow

Cumulative Sum using next column/row in R


I am having trouble with maybe something easy but I just can't find the solution.

Suppos I have an initial value of 1,000 for a variable called TOTAL and using another column I would like to do a cumulative sum, either negative or positive values.

The problem is that I do not want to do it manually but reproducible.

This is an expected output:

Profit  TOTAL
1  -10.0  990       #Started with 1,000
2   16.3 1006.3     #990 + 16.3
3  -10.0  996.3     #1006.3 - 10
4  -10.0  986.3     #And so on....
5   14.0 1000.3
6  -10.0  990.3

I tried to use cumsum function but I don't have an idea of how to implement it:

df %>% mutate(cumsum = cumsum(Profit)))

And I tried with sapply but I failed:

sapply(df[,c("TOTAL")], function(x) df$Profit[x+2] + df$TOTAL[x+1])

Any function, suggestion, or package that could solve this?


Solution

  • If I understand your right you need simply

    df=data.frame(profit=c(-10,16.3,-10,-10,14,-10))
    total=1000
    df$TOTAL=total+cumsum(df$profit)
    
     profit  TOTAL
    1  -10.0  990.0
    2   16.3 1006.3
    3  -10.0  996.3
    4  -10.0  986.3
    5   14.0 1000.3
    6  -10.0  990.3