簡體   English   中英

查找發生日期的時間間隔

[英]Finding the time interval in which a date occurs

我正在進行時間序列分析,希望開發具有不同分析單位的多個數據集。 即:數據集1中的單位將是X國在4年的跨度內的兩周期間(districtYearPeriodCode),數據集2中的單位將是X國在4年的跨度內的四周期間的區域4年,依此類推。

我創建了許多數據框,其中包含每個間隔的開始和結束日期,以及間隔ID。 以下是每兩周一次的間隔。

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包或其他線程中找到答案,但是所有答案似乎都是為了確定日期是否落在特定時間間隔內,而不是從一組間隔中確定日期落入的間隔而設計的。

非常感激!

我在這里使用@alistair概述的方法。 我在下面復制它:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM