I have the following dataframe:
df <- data.frame(id = c("1", "1", "1", "2", "2"),
x = c(12, 20, 24, 10, 14))
id x
1 12
1 20
1 24
2 10
2 14
I’d like to obain the lagged differences of x per id. The expected result:
id x
1 12
1 8
1 4
2 10
2 4
A dplyr solution is preferable.
Note that this question is not a duplicate, since the group refers to an ID in my case, not an unordered category.
>Solution :
Using diff
library(dplyr)
df %>%
mutate(x = c(x[1], diff(x)), .by = id)
id x
1 1 12
2 1 8
3 1 4
4 2 10
5 2 4