r - 我如何根据车牌号和时间离开加入 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
允许我按列值合并数据,但是如何设置日期时间在合适范围内的条件?
解决方案
这是使用data.table包的一种可能的非 equi 连接方法。如果 OP 只是在寻找一种tidyverse方法,我将把它记下来
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")]
推荐阅读
- python - 如何为 Keras 的 Conv2D 准备这些标签?ValueError: 预期的 dense_14 有 4 个维度
- docker - 使用主机网络从 docker 容器发送电子邮件
- sql - 基于日历表的以秒为单位的营业时间功能
- python - 如何在 QWidget 上添加背景图像并在其上添加位置 QLineedit?
- bash - 如何根据列拆分文件然后将该列放入 awk 或 bash
- android - 这些在 UI 线程上运行代码的方法有什么区别?
- javascript - Mongoose 在 [Mixed]-Arrays 的查询中自动插入“$in”
- angular - “对象”类型不存在属性“方向”
- javascript - 如何将 Post 请求发送到我做出反应的 php 文件?
- odoo - Odoo:是否可以为多个联系人使用同一个银行帐户?