在R中使用时间和地理坐标进行模糊连接 [英] Fuzzy Join Using Time and Geo-coordinates in R
问题描述
有两个数据帧,其信息完全不同。它们唯一的共同之处是日期时间和纬度/经度字段。是否可以使用R或R包(或可能的Python / Pandas)创建第三个数据框,该包从两个数据框中按相似的日期和经/纬度字段获取行的子集?连接应该是模糊的,而不是精确的,加上/减去一个小时和十分之一度。
There two data frames with disparate information. The only columns they have in common are datetime and lat/long fields. Can one create a third data frame using R or an R package (or possibly Python/Pandas) that takes a subset of rows from both data frames by similar date and lat/long fields? The joins should be fuzzy, not exact, plus/minus an hr and tenth a degree.
输入示例:
df_1
Datetime Latitude Longitude
2018-10-01 08:27:10 34.8014080 103.8499800
2018-09-30 04:55:51 43.3367432 44.158934
2018-02-28 17:03:27 37.0399910 115.6672080
df_2
Datetime Latitude Longitude
2018-10-01 08:57:10 34.8014080 103.8999800
2018-09-30 04:55:51 43.3367432 48.158934
2018-02-27 17:03:27 37.0399910 115.6672080
输出示例:
fuzzy_geo_temporal_join(df_1, df_2, time = 60, lat = 0.01, long = 0.01)
df_3
df_1 Datetime df_1 Lat df_1 Long df_2 Datetime df_2 Lat df_2 Long
2018-10-01 08:27:10 34.8014080 103.8499800 2018-10-01 08:57:10 34.8014080 103.8999800
注意:在此示例中,第一个匹配并放入新数据中F me子由于给定的模糊参数,第二个和第三个没有。
Note: In this example, the first one matches and gets placed into the new data frame. Due to the fuzzy parameters given, the second and third one do not.
推荐答案
这听起来像是对非装备的工作使用 data.table
!
This sounds like a job for a non-equi join, using data.table
!
library( data.table )
样本数据
dt1 <- fread( "Datetime, Latitude, Longitude
2018-10-01 08:27:10, 34.8014080, 103.8499800
2018-09-30 04:55:51, 43.3367432, 44.158934
2018-02-28 17:03:27, 37.0399910, 115.6672080", header = T)
dt2 <- fread("Datetime, Latitude, Longitude
2018-10-01 08:57:10, 34.8014080, 103.8999800
2018-09-30 04:55:51, 43.3367432, 48.158934
2018-02-27 17:03:27, 37.0399910, 115.6672080", header = T)
数据准备
#set datetimes to POSIXct
dt1[, Datetime := as.POSIXct( Datetime, format = "%Y-%m-%d %H:%M:%S") ]
dt2[, `:=`(Datetime = as.POSIXct( Datetime, format = "%Y-%m-%d %H:%M:%S" ) )]
加入
#create boundaries
dt2[, `:=`(Datetime_max = Datetime + 3600,
Datetime_min = Datetime - 3600,
Latitude_max = Latitude + 0.1,
Latitude_min = Latitude - 0.1,
Longitude_max = Longitude + 0.1,
Longitude_min = Longitude - 0.1) ]
#perform non-equi join
dt1[ dt2, on = .( Datetime <= Datetime_max,
Datetime >= Datetime_min,
Latitude <= Latitude_max,
Latitude >= Latitude_min,
Longitude <= Longitude_max,
Longitude >= Longitude_min ),
nomatch = 0L]
结果
# Datetime Latitude Longitude Datetime.1 Latitude.1 Longitude.1 i.Datetime i.Latitude i.Longitude
# 1: 2018-10-01 09:57:10 34.90141 104 2018-10-01 07:57:10 34.70141 103.8 2018-10-01 08:57:10 34.80141 103.9
这篇关于在R中使用时间和地理坐标进行模糊连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!