gpt4 book ai didi

r - 在列表中按时差查找日期

转载 作者:行者123 更新时间:2023-12-02 17:43:28 26 4
gpt4 key购买 nike

我被 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 天”标准的夫妇。

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

感谢您的帮助!

最佳答案

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

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"

关于r - 在列表中按时差查找日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com