2

我被 R 中的一个函数困住了。我有一个日期向量,我正在寻找间隔超过 5 天的几个日期。

这是我的向量的一部分:

    [1] "2011-10-06" "2011-09-28" "2011-09-20" "2011-08-29" "2011-09-09" "2011-08-16"
    [7] "2011-08-05" "2011-07-28" "2011-07-18" "2011-07-06" "2011-06-27" "2011-06-17"
    [13] "2011-06-03" "2011-05-22" "2011-05-02" "2011-05-12" "2011-04-21" "2011-04-11"
    [19] "2011-04-01" "2011-03-23

我知道如何计算向量中的时间差,如下所示:

dates <- as.list( c( "2011-10-06","2011-09-28","2011-09-20","2011-08-29","2011-09-09","2011-08-16","2011-08-05","2011-07-28","2011-07-18","2011-07-06","2011-06-27","2011-06-17","2011-06-03","2011-05-22","2011-05-02","2011-05-12","2011-04-21","2011-04-11","2011-04-01","2011-03-23" ) )
diff( as.Date( unlist(dates) ) )
#Time differences in days
# [1]  -8  -8 -22  11 -24 -11  -8 -10 -12  -9 -10 -14 -12 -20  10 -21 -10 -10  -9

我想要的是返回符合此标准的日期夫妇。例如,这对夫妇“2011-08-29”、“2011-09-09”是第一对满足我的向量中“时差> 5天”标准的夫妇。

有没有办法返回计算的情侣?也许使用向量中的项目数?

谢谢你的帮助!

4

1 回答 1

6

用于which测试您的 diff 向量以获取位置,并使用它从原始数据中选择值:

sel <- which(diff( as.Date( unlist(dates) ) )>5)

cbind(dates[sel],dates[sel+1])
     [,1]         [,2]        
[1,] "2011-08-29" "2011-09-09"
[2,] "2011-05-02" "2011-05-12"
于 2013-07-22T14:05:14.227 回答