可重现的例子:
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
using:
> idx <- sapply(d2$datetime,
+ function(x, start, end) {which(x > start & x < end)},
+ d1$start, d1$end)
> idx
[1] 1 2 3
我们可以使用索引idx
绑定元素d1
on to 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