2017-08-25 85 views
1

我正在進行時間序列分析,我希望能夠用不同的分析單位開發多個數據集。即:數據集1中的單位將是X國的區域,爲期4年(districtYearPeriodCode)中的2周時間段,數據集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包,或在其他線程的答案,但所有的答案似乎在特定的時間間隔內找出一個日期是否下降,而不是確定的時間間隔進行調整一個日期來自一組間隔。

很多appreiciated!

+0

喜歡的東西:https://stackoverflow.com/questions/41132081/find-which-interval-row-in-a-data-frame-that-each-element-of- a-vector-belong-in/41133991也許? – thelatemail

+0

是的,它的工作! – srojascabal

回答

0

我使用了@alistair在here概述的purrr。我複製它下面:

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"