首页 > 解决方案 > 在 data.table 的区间内按日期选择行

问题描述

我想在数据表中选择属于第二个数据表中指定的时间间隔内的观察值 - 间隔是同时从 2 个平台进行观察的时间段。

第一个数据表看起来像这样。这是一堆动物目击事件。

obs = data.table(sighting = as.POSIXct(c("2018-08-12 16:30:00", "2018-08-12 16:35:00", "2018-08-12 16:38:00", "2107-08-13 15:13:00", "2107-08-13 16:13:00", "2017-08-14 11:12:13"), format = "%Y-%m-%d %H:%M:%OS", tz = "America/Halifax"), encounter = c("1", "1", "1", "2", "3", "4"), what = c("frog", "frog", "toad", "bird", "goat","bird"))

从 2 个平台进行观察。

platformA = data.table(station = "A", on.effort = as.POSIXct(c("2018-08-12 16:00:00", "2018-08-12 17:35:00","2017-08-14 11:00:13", "2018-08-15 17:35:00"), format = "%Y-%m-%d %H:%M:%OS", tz = "America/Halifax"), off.effort = as.POSIXct(c("2018-08-12 16:36:00", "2018-08-12 18:35:00","2017-08-14 12:12:13", "2018-08-15 18:35:00"), format = "%Y-%m-%d %H:%M:%OS", tz = "America/Halifax"))

platformB = data.table(station = "B", on.effort = as.POSIXct(c("2018-08-12 16:15:00", "2018-08-12 17:40:00", "2018-08-13 17:40:00","2017-08-14 11:05:13"), format = "%Y-%m-%d %H:%M:%OS", tz = "America/Halifax"), off.effort = as.POSIXct(c("2018-08-12 16:40:00", "2018-08-13 17:45:00", "2018-08-12 18:20:00","2017-08-14 12:30:13"), format = "%Y-%m-%d %H:%M:%OS", tz = "America/Halifax"))

我首先计算了每个平台的间隔,然后将这些间隔相交以找出同时进行观察的时间。

setkey(platformA, on.effort, off.effort)
setkey(platformB, on.effort, off.effort)

common = foverlaps(platformA, platformB,type="any",nomatch=0)

common$x = intersect(interval(common$on.effort, common$off.effort), 
                     interval(common$i.on.effort, common$i.off.effort))

我想最终得到一个表,它是“obs”的子集,并且只包含“common$x”中的间隔所覆盖的行。我曾希望使用 foverlaps 找到相交间隔中的行,并为我的目击创建“点”间隔

obs[, sighting2 := sighting]

但是 foverlaps 想要每个间隔的“开始”和“结束”在单独的列中,这不是间隔存储在 common$x 中的方式。

我希望我的输出看起来像这样

           sighting encounter what
2018-08-12 16:30:00         1 frog
2018-08-12 16:35:00         1 frog
2017-08-14 11:12:13         4 bird

我会很感激任何提示。也许我之前可以更有效率?谢谢。

标签: rdata.tableposixoverlap

解决方案


我认为即使您在平台之间有不同的观察数字,这也应该有效。如上所述使用您的obs,platformAplatformB数据,或多或少地为两个平台设置间隔,就像您在上面所做的那样common

common = intersect(interval(platformA$on.effort, platformA$off.effort), 
                   interval(platformB$on.effort, platformB$off.effort))

您应该能够使用%within%来检查是否存在目击事件属于共同间隔的情况:

obs$both.seen <- sapply(obs$sighting, function(s){
  any(s %within% common)
})

或者

obs[, both.seen := sapply(sighting, function(x) any(x %within% common))]

obs

> obs
              sighting encounter what both.seen
1: 2018-08-12 16:30:00         1 frog      TRUE
2: 2018-08-12 16:35:00         1 frog      TRUE
3: 2018-08-12 16:38:00         1 toad     FALSE
4: 2107-08-13 15:13:00         2 bird     FALSE
5: 2107-08-13 16:13:00         3 goat     FALSE
6: 2017-08-14 11:12:13         4 bird      TRUE

获得所需输出的子集:

obs <- obs[both.seen == 1][, both.seen := NULL][]

> obs
              sighting encounter what
1: 2018-08-12 16:30:00         1 frog
2: 2018-08-12 16:35:00         1 frog
3: 2017-08-14 11:12:13         4 bird

推荐阅读