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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With