I would like to calculate the date difference between each entry. The data looks like this
> dt <- data.table(id = c("A", "A", "A", "B", "B", "B", "C", "C", "C"), date = as.Date(c("2017-01-01", "2017-02-01", "2017-05-01", "2017-01-01", "2017-05-01", "2017-10-01", "2017-01-01", "2017-02-01", "2017-02-15")))
> dt
id date
1: A 2017-01-01
2: A 2017-02-01
3: A 2017-05-01
4: B 2017-01-01
5: B 2017-05-01
6: B 2017-10-01
7: C 2017-01-01
8: C 2017-02-01
9: C 2017-02-15
and what I want to get is sth looks like following, how should I construct var "Diff"?
Update:
I tried to solve this by using following codes:
> dt <- data.table(id = c("A", "A", "A", "B", "B", "B", "C", "C", "C"), date = as.Date(c("2017-01-01", "2017-02-01", "2017-05-01", "2017-01-01", "2017-05-01", "2017-10-01", "2017-01-01", "2017-02-01", "2017-02-15")))
> dt %>%
+ group_by(id) %>%
+ mutate(diff = date - lag(date))
# A tibble: 9 x 3
# Groups: id [3]
id date diff
<chr> <date> <drtn>
1 A 2017-01-01 NA days
2 A 2017-02-01 31 days
3 A 2017-05-01 89 days
4 B 2017-01-01 -120 days
5 B 2017-05-01 120 days
6 B 2017-10-01 153 days
7 C 2017-01-01 -273 days
8 C 2017-02-01 31 days
9 C 2017-02-15 14 days
I am not sure what I did wrong. Any idea?