R:快速计数与条件向量匹配的行

时间:2018-02-13 16:13:52

标签: r data.table vectorization

我有数据

dt <- data.table(beg=as.POSIXct(c("2018-01-01 01:01:00","2018-01-01 01:05:00","2018-01-01 01:08:00")), end=as.POSIXct(c("2018-01-01 01:10:00","2018-01-01 01:10:00","2018-01-01 01:10:00")))
> dt
                   beg                 end
1: 2018-01-01 01:01:00 2018-01-01 01:10:00
2: 2018-01-01 01:05:00 2018-01-01 01:10:00
3: 2018-01-01 01:08:00 2018-01-01 01:10:00

times <- seq(from=min(dt$beg),to=max(dt$end),by="mins")

我希望尽可能高效地计算每次times df中有多少时间间隔。

我理解

count <- NA
for(i in 1:length(times)){
   count[i] <- sum(dt$beg<times[i] & dt$end>times[i])
}

会产生解决方案

> data.table(times, count)
                   time count
 1: 2018-01-01 01:01:00     0
 2: 2018-01-01 01:02:00     1
 3: 2018-01-01 01:03:00     1
 4: 2018-01-01 01:04:00     1
 5: 2018-01-01 01:05:00     1
 6: 2018-01-01 01:06:00     2
 7: 2018-01-01 01:07:00     2
 8: 2018-01-01 01:08:00     2
 9: 2018-01-01 01:09:00     3
10: 2018-01-01 01:10:00     0

但我想知道是否有更节省时间的解决方案,例如使用data.table。

1 个答案:

答案 0 :(得分:2)

这可以是一个解决方案

times = as.data.table(times)
ans = dt[times, .(x.beg, x.end, i.x),on = .(beg < x , end > x),allow.cartesian = TRUE]
ans[,sum(!is.na(x.end)), by = .(i.x)]
                    i.x V1
 1: 2018-01-01 01:01:00  0
 2: 2018-01-01 01:02:00  1
 3: 2018-01-01 01:03:00  1
 4: 2018-01-01 01:04:00  1
 5: 2018-01-01 01:05:00  1
 6: 2018-01-01 01:06:00  2
 7: 2018-01-01 01:07:00  2
 8: 2018-01-01 01:08:00  2
 9: 2018-01-01 01:09:00  3
10: 2018-01-01 01:10:00  0

干杯!

相关问题