如何在 R 中查找两个日期之间的天数和周数?
在数据分析中,时间序列是我们必须处理的常见数据类型之一,它可能包含日期数据以及其他变量。我们可能希望查找两个时间之间的差异,以检查有多少天或周的时间序列发生了变化。这可以通过 difftime 函数轻松完成。
示例
> difftime(strptime("25/07/2021", format = "%d/%m/%Y"), + strptime("25/07/2020", format = "%d/%m/%Y"),units="weeks") Time difference of 52.14286 weeks > difftime(strptime("25.07.2021", format = "%d.%m.%Y"), + strptime("25.07.2020", format = "%d.%m.%Y"),units="weeks") Time difference of 52.14286 weeks > difftime(strptime("25.07.2021", format = "%d.%m.%Y"), + strptime("25.07.2020", format = "%d.%m.%Y")) Time difference of 365 days > difftime(strptime("01.01.2021", format = "%d.%m.%Y"), + strptime("25.07.2020", format = "%d.%m.%Y")) Time difference of 160 days > difftime(strptime("01.01.2021", format = "%d.%m.%Y"), + strptime("25.07.2020", format = "%d.%m.%Y"),units="weeks") Time difference of 22.85714 weeks > difftime(strptime("01.01.2050", format = "%d.%m.%Y"), + strptime("01.01.2020", format = "%d.%m.%Y")) Time difference of 10958 days > difftime(strptime("01.01.2050", format = "%d.%m.%Y"), + strptime("01.01.2020", format = "%d.%m.%Y"),units="weeks") Time difference of 1565.429 weeks > difftime(strptime("01.01.2030", format = "%d.%m.%Y"), + strptime("01.01.2020", format = "%d.%m.%Y"),units="weeks") Time difference of 521.8571 weeks > difftime(strptime("01.01.2030", format = "%d.%m.%Y"), + strptime("01.01.2020", format = "%d.%m.%Y")) Time difference of 3653 days > difftime(strptime("25/12/2021", format = "%d/%m/%Y"), + strptime("01/01/2021", format = "%d/%m/%Y"),units="weeks") Time difference of 51.14286 weeks > difftime(strptime("25/12/2021", format = "%d/%m/%Y"), + strptime("01/01/2021", format = "%d/%m/%Y")) Time difference of 358 days > difftime(strptime("01/01/3000", format = "%d/%m/%Y"), + strptime("01/01/2000", format = "%d/%m/%Y")) Time difference of 365243 days > difftime(strptime("01/01/3000", format = "%d/%m/%Y"), + strptime("01/01/2000", format = "%d/%m/%Y"),units="weeks") Time difference of 52177.57 weeks > difftime(strptime("01/01/0001", format = "%d/%m/%Y"), + strptime("25/07/2020", format = "%d/%m/%Y")) Time difference of -737630 days > difftime(strptime("01/01/0001", format = "%d/%m/%Y"), + strptime("25/07/2020", format = "%d/%m/%Y"),units="weeks") Time difference of -105375.7 weeks
广告