I have a df like this in R:
A | B |
---|---|
a | 6 |
b | 13 |
c | 9 |
c | 16 |
c | 17 |
c | 23 |
I want a new column df$C, which substracts the value in B2 from the value in B1, if A2 = A1 and substracts the value in B3 from the value in B2, if A3 = A2 and so on ... Just like this:
A | B | C |
---|---|---|
a | 6 | 6 |
b | 13 | 13 |
c | 9 | 9 |
c | 16 | 7 |
c | 17 | 1 |
c | 23 | 6 |
I tried to write a simple ifelse-function, but don't know how I can compare two consecutively values in the same column.