【问题标题】:Finding the time interval in which a date occurs查找日期发生的时间间隔
【发布时间】:2017-08-25 05:52:41
【问题描述】:

我正在进行时间序列分析,我希望开发具有不同分析单元的多个数据集。即:数据集 1 中的单位将是 X 国在 4 年内为期 2 周的地区(districtYearPeriodCode),数据集 2 中的单位将是 X 国在 4 周内的地区,跨度为4 年,以此类推。

我创建了许多数据框,其中包含每个间隔的开始日期和结束日期,以及一个间隔 ID。以下是 2 周的间隔。

begin <- seq(ymd('2004-01-01'),ymd('2004-06-30'), by = as.difftime(weeks(2)))
end <- seq(ymd('2004-01-14'),ymd('2004-06-30'), by = as.difftime(weeks(2)))
interval <- seq(1,13,1)
df2 <- data.frame(begin, end, interval)

        begin        end interval
1  2004-01-01 2004-01-14        1
2  2004-01-15 2004-01-28        2
3  2004-01-29 2004-02-11        3
4  2004-02-12 2004-02-25        4
5  2004-02-26 2004-03-10        5
6  2004-03-11 2004-03-24        6
7  2004-03-25 2004-04-07        7
8  2004-04-08 2004-04-21        8
9  2004-04-22 2004-05-05        9
10 2004-05-06 2004-05-19       10
11 2004-05-20 2004-06-02       11
12 2004-06-03 2004-06-16       12
13 2004-06-17 2004-06-30       13

除此之外,我还有一个数据框,其中包含对事件的观察,包括日期。它看起来像这样:

new.df3 <- data.frame(dates5, districts5)
new.df3

  dates5 districts5
1 2004-01-01         d1
2 2004-01-02         d2
3 2004-01-03         d3
4 2004-01-04         d4
5 2004-01-05         d5

是否有我可以编写的函数或可以使用的命令来完成类似的操作?

      dates5 districts5 interval5
1 2004-01-01         d1         1
2 2004-01-02         d2         1
3 2004-01-03         d3         1
4 2004-01-04         d4         1
5 2004-01-05         d5         1

我一直试图在 lubridate 包或其他线程中找到答案,但所有答案似乎都是为了确定日期是否在特定时间间隔内而不是识别日期从一组间隔中落入的间隔。

非常感谢!

【问题讨论】:

标签: r date intervals lubridate


【解决方案1】:

我使用了@alistair 在here 中概述的呼噜声。我在下面复制它:

elements %>% 
    map(~intervals$phase[.x >= intervals$start & .x <= intervals$end]) %>% 
    # Clean up a bit. Shorter, but less readable: map_chr(~.x[1] %||% NA)
    map_chr(~ifelse(length(.x) == 0, NA, .x))
## [1] "a" "a" "a" NA  "b" "b" "c"

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多