Cumulative sum loop with if statement

Viewed 204

I have something like the following data frame in R. I want to create a loop that creates a cumulative sum with with first incoming amount as the initial balance, and then subtracts when an amount is outgoing and adds when an amount is incoming. Any idea how to do this in R would be appreciated.

Seq<-c(1,2,3,4,5)
Direction<-c("INCOMING","OUTGOING", "INCOMING", "OUTGOING", "OUTGOING")
Amount<-c(500,200,300,400,200)
df<-cbind(Seq, Direction, Amount)
2 Answers

You can use cumsum and an equality to check wether you have to add or substract:

df <- data.frame(Seq, Direction, Amount)
df

cumsum(df$Amount * ifelse(df$Direction == "INCOMING", 1, -1))
[1] 500 300 600 200   0

Try this base R code

transform(
    df,
    bal = cumsum(Amount * (2 * (Direction == "INCOMING") - 1))
)

which gives

  Seq Direction Amount bal
1   1  INCOMING    500 500
2   2  OUTGOING    200 300
3   3  INCOMING    300 600
4   4  OUTGOING    400 200
5   5  OUTGOING    200   0
Related