Given Date in date frame:
Date: Note it's in year/month/day format
2020-01-01
2020-02-01
2020-03-03
2020-04-04
How do I get the aggregate count total of number of days between each date.
Count:
0
30
58
87
Given Date in date frame:
Date: Note it's in year/month/day format
2020-01-01
2020-02-01
2020-03-03
2020-04-04
How do I get the aggregate count total of number of days between each date.
Count:
0
30
58
87
Just convert the character strings to a Date
object.
dates <- as.Date(c("2020-01-01", "2020-02-01", "2020-03-03", "2020-04-04"))
dates - dates[1]
# Time differences in days
# [1] 0 31 62 94
you can convert your character strings to date format using as.Date
and then use the lag
function:
df <- data.frame(date = c("2020-01-01", "2020-02-02", "2020-03-03", "2020-04-04"))
df$ndays <- as.numeric(as.Date(df$date) - dplyr::lag(as.Date(df$date), n = 1, default = as.Date(df$date)[1]))
> df
date ndays
1 2020-01-01 0
2 2020-02-02 32
3 2020-03-03 30
4 2020-04-04 32