【发布时间】:2020-10-19 20:41:30
【问题描述】:
日期框架中的给定日期:
Date: Note it's in year/month/day format
2020-01-01
2020-02-01
2020-03-03
2020-04-04
如何获得每个日期之间的总天数。
Count:
0
30
58
87
【问题讨论】:
日期框架中的给定日期:
Date: Note it's in year/month/day format
2020-01-01
2020-02-01
2020-03-03
2020-04-04
如何获得每个日期之间的总天数。
Count:
0
30
58
87
【问题讨论】:
只需将字符串转换为Date 对象。
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
【讨论】:
您可以使用as.Date 将字符串转换为日期格式,然后使用lag 函数:
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
【讨论】: