mydata<-data.frame(
ID=c(1,1,1,1,2,2,2,3,3,3),
day=c(2,4,7,22,8,9,22,4,7,17))
In this dataset, I have 3 patients who have 3 or 4 follow-up points. I want to calculate the number of days between each follow-up point and the previous one. I need to have such a table, the difference for the first row after sorting days un increasing way, should be 0
ID day diff
1 1 2 0
2 1 4 2
3 1 7 3
4 1 22 15
5 2 8 0
6 2 9 1
7 2 22 13
8 3 4 0
9 3 7 3
10 3 17 10
Thanks for your help