2011-02-25 151 views
2

StackOverflow-匹配時間的開始和結束時間

院士ř用戶我有一組不同的時間匹配於由開始和結束在另一個數據幀界定的時間間隔之間的間隔的時間。這將導致一個數據框與多對一的關係。

一組簡化的記錄將比賽拖入如下:

 vid    start     end 
17599 7588 2011-02-14 19:00:00 2011-02-14 19:11:00 
17601 7588 2011-02-14 19:58:00 2011-02-14 20:43:00 
17603 7588 2011-02-14 21:22:00 2011-02-14 22:00:00 

而且一些示例記錄,以匹配上面的數據是:

 vid   datetime 
469818 7588 2011-02-14 19:00:10 
470747 7588 2011-02-14 19:59:10 
470788 7588 2011-02-14 21:23:10 

我想是這樣的:

 vid   datetime    start     end 
     7588 2011-02-14 19:00:10 2011-02-14 19:00:00 2011-02-14 19:11:00 
     7588 2011-02-14 19:59:10 2011-02-14 19:58:00 2011-02-14 20:43:00 
     7588 2011-02-14 21:23:10 2011-02-14 21:22:00 2011-02-14 22:00:00 

對於我的生活,我無法弄清楚如何做到這一點的R.任何幫助GR吃得津津樂道。謝謝!

回答

1

但是我解決了這個問題,使用split()分割數據後,使用> =和< =運算符來比較開始,結束和日期時間字段。 ; match.col = with(d2[[v]], d1$datetime >= d2.start & d1$datetime <= d2.end)

1

重複的例子:

txt1 <- "  vid    start     end 
17599 7588 '2011-02-14 19:00:00' '2011-02-14 19:11:00' 
17601 7588 '2011-02-14 19:58:00' '2011-02-14 20:43:00' 
17603 7588 '2011-02-14 21:22:00' '2011-02-14 22:00:00' 
" 
txt2 <- "  vid   datetime 
469818 7588 '2011-02-14 19:00:10' 
470747 7588 '2011-02-14 19:59:10' 
470788 7588 '2011-02-14 21:23:10' 
" 
d1 <- read.table(textConnection(txt1), header = TRUE, 
       colClasses = c("integer","integer","POSIXct","POSIXct")) 
d2 <- read.table(textConnection(txt2), header = TRUE, 
       colClasses = c("integer","integer","POSIXct")) 

我們可以在d1對應的d2每一行的索引(行)使用get:

> idx <- sapply(d2$datetime, 
+    function(x, start, end) {which(x > start & x < end)}, 
+    d1$start, d1$end) 
> idx 
[1] 1 2 3 

而且我們可以使用索引idx綁定元素d1轉至d2

> cbind(d2, d1[idx, 2:3]) 
     vid   datetime    start     end 
469818 7588 2011-02-14 19:00:10 2011-02-14 19:00:00 2011-02-14 19:11:00 
470747 7588 2011-02-14 19:59:10 2011-02-14 19:58:00 2011-02-14 20:43:00 
470788 7588 2011-02-14 21:23:10 2011-02-14 21:22:00 2011-02-14 22:00:00 
+1

感謝您的回答,Gavin。也許我在最初的聲明中並不清楚,但我需要進行多對一的匹配,並且數據無法像我的示例那樣保證排序。 但我解決了這個問題,使用> =和<=運算符來比較開始,結束和日期時間字段。 match.col = with(d2 [[v]],d1 $ datetime> = d2.start&d1 $ datetime <= d2.end); – 2011-03-01 18:24:25

相關問題