如何找到R数据框的两个日期列之间的天数差异?

处理日期数据时,如果数据包含两个或多个日期值,我们通常希望查找日期之间的差异。可以对包含日期的R数据框的两列执行相同的操作,但是首先,我们需要以日期格式读取这些日期列,以防万一它们未记录为R中的日期。通过使用difftime函数来完成。

示例

请看以下数据-

date1<-c("2020/02/02","2020/02/04","2020/02/05","2020/02/06","2020/02/08","2020/02/12","2020/02/13","2020/02/15","2020/02/16","2020/02/17","2020/02/18","2020/02/19","2020/02/20","2020/02/22","2020/02/23","2020/02/24","2020/02/25","2020/02/26","2020/02/27","2020/03/01")
date1
[1] "2020/02/02" "2020/02/04" "2020/02/05" "2020/02/06" "2020/02/08"
[6] "2020/02/12" "2020/02/13" "2020/02/15" "2020/02/16" "2020/02/17"
[11] "2020/02/18" "2020/02/19" "2020/02/20" "2020/02/22" "2020/02/23"
[16] "2020/02/24" "2020/02/25" "2020/02/26" "2020/02/27" "2020/03/01"
date2<-c("2020/03/02","2020/03/03","2020/03/05","2020/03/06","2020/03/07","2020/03/08","2020/03/10","2020/03/13","2020/03/14","2020/03/15","2020/03/16","2020/03/17","2020/03/18","2020/03/20","2020/03/21","2020/03/22","2020/03/23","2020/03/24","2020/03/26","2020/03/27")
date2
[1] "2020/03/02" "2020/03/03" "2020/03/05" "2020/03/06" "2020/03/07"
[6] "2020/03/08" "2020/03/10" "2020/03/13" "2020/03/14" "2020/03/15"
[11] "2020/03/16" "2020/03/17" "2020/03/18" "2020/03/20" "2020/03/21"
[16] "2020/03/22" "2020/03/23" "2020/03/24" "2020/03/26" "2020/03/27"
df<-data.frame(date1,date2)
df

输出结果

date1 date2
1 2020/02/02 2020/03/02
2 2020/02/04 2020/03/03
3 2020/02/05 2020/03/05
4 2020/02/06 2020/03/06
5 2020/02/08 2020/03/07
6 2020/02/12 2020/03/08
7 2020/02/13 2020/03/10
8 2020/02/15 2020/03/13
9 2020/02/16 2020/03/14
10 2020/02/17 2020/03/15
11 2020/02/18 2020/03/16
12 2020/02/19 2020/03/17
13 2020/02/20 2020/03/18
14 2020/02/22 2020/03/20
15 2020/02/23 2020/03/21
16 2020/02/24 2020/03/22
17 2020/02/25 2020/03/23
18 2020/02/26 2020/03/24
19 2020/02/27 2020/03/26
20 2020/03/01 2020/03/27

将date1和date2的格式更改为日期格式-

示例

df$date1<-as.Date(df$date1,format="%Y/%m/%d")
df$date2<-as.Date(df$date2,format="%Y/%m/%d")

找到两个日期之间的天数差异-

示例

df$Date_difference_in_days <-difftime(df$date1,df$date2,units=c("days"))
df

输出结果

date1 date2 Date_difference_in_days
1 2020-02-02 2020-03-02 -29 days
2 2020-02-04 2020-03-03 -28 days
3 2020-02-05 2020-03-05 -29 days
4 2020-02-06 2020-03-06 -29 days
5 2020-02-08 2020-03-07 -28 days
6 2020-02-12 2020-03-08 -25 days
7 2020-02-13 2020-03-10 -26 days
8 2020-02-15 2020-03-13 -27 days
9 2020-02-16 2020-03-14 -27 days
10 2020-02-17 2020-03-15 -27 days
11 2020-02-18 2020-03-16 -27 days
12 2020-02-19 2020-03-17 -27 days
13 2020-02-20 2020-03-18 -27 days
14 2020-02-22 2020-03-20 -27 days
15 2020-02-23 2020-03-21 -27 days
16 2020-02-24 2020-03-22 -27 days
17 2020-02-25 2020-03-23 -27 days
18 2020-02-26 2020-03-24 -27 days
19 2020-02-27 2020-03-26 -28 days
20 2020-03-01 2020-03-27 -26 days