首页 > 解决方案 > 我如何根据车牌号和时间离开加入 2 个不同的表?

问题描述

我是 R 新手,并试图根据车牌号和日期时间加入 2 组数据。

数据集 1

LicensePlate DateTime
XLP1234P     09-JUN-18 02.52.40.144000000 PM
XLP2345P     18-JUL-18 11.22.46.855000000 AM
XLP3456P     18-JUL-18 11.22.46.856000000 AM
XLP4567P     18-JUL-18 11.22.46.856000000 AM
XLP5678P     18-JUL-18 11.22.46.857000000 AM
XLP6789P     18-JUL-18 11.22.46.858000000 AM

数据集 2

LicensePlate DateTime
XLP1234P     09-JUN-18 02.55.40.144000000 PM 
XLP2345P     18-JUL-18 11.30.46.855000000 AM

基本上,数据集是由两套不同的设备记录的,因此会有轻微的时间差异。我想以可接受的 10 分钟时差根据车牌离开加入第一组。

left_join允许我按列值合并数据,但是如何设置日期时间在合适范围内的条件?

标签: r

解决方案


包的一种可能的非 equi 连接方法。方法,我将把它记下来

DT1[, c("start", "end") := .(DateTime - 60*10, DateTime + 60*10)]
DT2[DT1, on=.(LicensePlate=LicensePlate, DateTime>=start, DateTime<=end),
    .(LicensePlate, i.DateTime, x.DateTime)]

输出:

   LicensePlate          i.DateTime          x.DateTime
1:     XLP1234P 2018-06-09 02:52:40 2018-06-09 02:55:40
2:     XLP2345P 2018-07-18 11:22:46 2018-07-18 11:30:46
3:     XLP3456P 2018-07-18 11:22:46                <NA>
4:     XLP4567P 2018-07-18 11:22:46                <NA>
5:     XLP5678P 2018-07-18 11:22:46                <NA>
6:     XLP6789P 2018-07-18 11:22:46                <NA>

数据:

library(data.table)
DT1 <- fread("LicensePlate,DateTime 
XLP1234P,09-JUN-18 02.52.40.144000000 PM 
XLP2345P,18-JUL-18 11.22.46.855000000 AM 
XLP3456P,18-JUL-18 11.22.46.856000000 AM 
XLP4567P,18-JUL-18 11.22.46.856000000 AM 
XLP5678P,18-JUL-18 11.22.46.857000000 AM 
XLP6789P,18-JUL-18 11.22.46.858000000 AM")

DT2 <- fread("LicensePlate,DateTime
XLP1234P,09-JUN-18 02.55.40.144000000 PM 
XLP2345P,18-JUL-18 11.30.46.855000000 AM")

DT1[, DateTime := as.POSIXct(DateTime, format="%d-%b-%y %H.%M.%OS")]
DT2[, DateTime := as.POSIXct(DateTime, format="%d-%b-%y %H.%M.%OS")]

推荐阅读