按时间差列表查找日期

时间:2013-07-22 13:57:46

标签: r

我在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”是第一对在我的载体中满足“时差&gt; 5天”标准的夫妇。

有没有办法归还计算出来的情侣?也许使用向量中的项目数?

感谢您的帮助!

1 个答案:

答案 0 :(得分: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"