Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add value to previous row if condition is met

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
like image 756
grig109 Avatar asked Jan 01 '17 22:01

grig109


1 Answers

Another approach

df <- data.frame(a=c(0, 1, 2, 2, 3),
             b=c(1, 3, 2, 4, 4))

df$a[c(df$b[-1], 0) == 2] <- df$a[c(df$b[-1], 0) == 2] + 3
like image 149
dimitris_ps Avatar answered Oct 11 '22 13:10

dimitris_ps