1

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
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Jayloy Tsu
  • 31
  • 5
  • Possibly related: [Calculating number of days between 2 columns of dates in data frame](https://stackoverflow.com/questions/11666172/calculating-number-of-days-between-2-columns-of-dates-in-data-frame) – SecretAgentMan Oct 19 '20 at 21:02

2 Answers2

2

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
dcarlson
  • 10,936
  • 2
  • 15
  • 18
0

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
Cettt
  • 11,460
  • 7
  • 35
  • 58