dimanche 1 janvier 2017

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])

Aucun commentaire:

Enregistrer un commentaire