I have the following df:
df = data.frame(id=c(1,1,1,1,1,1),
date=c(as.Date("2000-01-01"), as.Date("2000-07-11"),
as.Date("2000-08-01"), as.Date("2000-12-31"),
as.Date("2002-05-04"), as.Date("2002-06-01")))
I need the following result:
result = data.frame(id=c(1,1,1,1,1,1),
date=c(as.Date("2000-01-01"), as.Date("2000-07-11"),
as.Date("2000-08-01"), as.Date("2000-12-31"),
as.Date("2002-05-04"), as.Date("2002-06-01")),
days_91 = c(0,0,1,0,0,1),
days_182 = c(0,0,1,0,0,1),
days_273 = c(0,1,1,1,0,1),
days_365 = c(0,1,1,1,0,1))
Basically, for a certain date I want to know if a prior dates exists for the same ID in the last X days.
I supposed a lubridate fuction must exist but did not find it.
Result:
| id | date | days_91 | days_182 | days_273 | days_365 |
|---|---|---|---|---|---|
| 1 | 2000-01-01 | 0 | 0 | 0 | 0 |
| 1 | 2000-07-11 | 0 | 0 | 1 | 1 |
| 1 | 2000-08-01 | 1 | 1 | 1 | 1 |
| 1 | 2000-12-31 | 0 | 1 | 1 | 1 |
| 1 | 2002-05-04 | 0 | 0 | 0 | 0 |
| 1 | 2002-06-01 | 1 | 1 | 1 | 1 |
For instance, for row 3 there is a previous date in the last 91, 182, 273 and 365 days. However in row 2 there is no previous visit in the last 91 and 182 days