I'm trying to calculate the difference in days of my rows to create interval.
My data set called temp
looks like this,
ID Event
31933 11/12/2016
31933 11/14/2016
31750 09/04/2016
31750 09/10/2016
31750 09/30/2016
31750 10/01/2016
30995 09/04/2016
30995 09/09/2016
30995 09/10/2016
30995 9/24/2016
So my question is how can I calculate the difference between dates in day by ID? So for ID 31933 it is 2 days and for 31750 6, 20 and 1 days. I've tried several options which were given in other examples here, such as
library(zoo)
setDT(temp)
Interval<- function(x) difftime(x[3], x[1],units = "days")
temp[, INTERVAL := rollapply(Event, 3, diff, align = "left", fill = NA), by= ID]
The error here was "Type of RHS ('double') must match LHS ('logical')
. To check and coerce would impact performance too much for the fastest cases. Either change the type of the target column, or coerce the RHS
of := yourself (e.g. by using 1L instead of 1)"
Also tried a few data.table functions but they did not work.
I'm quite new to R, so I suppose there is a simple solution.