What I am trying to do is if a row in column b is equal to 2 then I want to add 3 to the value of the previous row in column a. And if the condition is not met, then I don't want the previous row value to change. When I try this code however R is adding to the subsequent row. And it doesn't matter what I replace the -1 row reference with it always adds to the subsequent row.
df$a[-1] <- ifelse(df$b == 2, df$a[-1] + 3, df$a[-1])
Have Want
a b a b
0 1 0 1
1 3 4 3
2 2 2 2
2 4 2 4
4 5 4 5