我有两个独立的数据表,我想找到从一个数据表到另一个数据表的最靠近的邮政编码。从 SiteZip 表中,我希望邮政编码循环遍历 ConsumerZip 表以获得邮政编码之间的最短距离。我使用 zipcodeR 包为其分配纬度和经度。两个表如下。第一个表是商店的位置。另一个表是客户位置。我希望能够创建一个表来显示每个客户最近的商店。我研究了几天,没有发现很多符合我要找的请求。最终,我将根据客户位置用密度圈来绘制商店位置。预先感谢您提供的任何帮助。
head(StoreZip)
Zip Store Address1 City State lat lng
1: 01026 11111 151 South Street Cummington MA 42.48 -72.93
2: 01040 11112 303 Beech St. Holyoke MA 42.22 -72.64
3: 01104 11113 417 Liberty St. Springfield MA 42.13 -72.57
4: 01104 11114 2155 Main St. Springfield MA 42.13 -72.57
5: 01301 11115 55 Federal St. Greenfield MA 42.63 -72.59
6: 01301 11116 1 Arch Place Greenfield MA 42.63 -72.59```
```head(CustomersZip)
Zip ID Address1 City State lat lng
1: 01001 65484654805 1548 MAIN STREET AGAWAM MA 42.07 -72.63
2: 01001 64846124846 569 MAPLE ST AGAWAM MA 42.07 -72.63
3: 01001 68421548945 68 PLANTATION DR AGAWAM MA 42.07 -72.63
4: 01001 84051545484 154 South DR AGAWAM MA 42.07 -72.63
5: 01001 97545154848 985 Main St AGAWAM MA 42.07 -72.63
6: 01002 64841515484 54 KING ST PELHAM MA 42.38 -72.52
最佳答案
这里有一个映射每个 CustomersZip$ID
的解决方案与最近的StoreZip$Store
:
library(data.table)
# library(geosphere) # distHaversine
CustomersZip[
, Store := StoreZip$Store[
which.min(geosphere::distHaversine(
cbind(first(lng), first(lat)),
StoreZip[, cbind("lng", "lat"), with = FALSE])) ]
, by = ID ]
CustomersZip
# Zip ID lat lng Store
# <int> <char> <num> <num> <int>
# 1: 1001 65484654805 42.07 -72.63 11113
# 2: 1001 64846124846 42.07 -72.63 11113
# 3: 1001 68421548945 42.07 -72.63 11113
# 4: 1001 84051545484 42.07 -72.63 11113
# 5: 1001 97545154848 42.07 -72.63 11113
# 6: 1002 64841515484 42.38 -72.52 11112
演练:
-
distHaversine
对两个参数进行操作,通常是每个都有两列的矩阵(或框架);它如何计算距离取决于每个参数中的点数p1
和p2
:- 如果
p1
有一个点,然后它计算所有p2
指向个人p1
观点;类似地如果p2
有 1 分; - 如果
p1
和p2
具有相同数量的点,它逐点计算距离,使得 row1 与 row1,row2 与 row2,等等;它不对“row1 with row1,row2,row3,...”、“row2 with row1,row2,row3,...”进行笛卡尔展开,所以这必须在外部发生里>
- 如果
- 因此,我们一次为一位客户服务,并找到距离最小的商店 (
which.min
) 并存储其Store
id - 虽然不是此示例数据的一个因素,但我选择按
CustomersZip$ID
对其进行分组并仅使用first
为该客户找到了纬度/经度;如果客户可能有不同的积分,则删除first
调用电话,并通过by = seq_len(nrow(CustomersZip))
进行分组反而;如果不需要这一步,它仍然会计算出相同的结果,唯一的损失是多次计算相同的距离会带来一些效率
可重复使用的数据(问题中的数据的子集):
StoreZip <- fread("
Zip Store lat lng
01026 11111 42.48 -72.93
01040 11112 42.22 -72.64
01104 11113 42.13 -72.57
01104 11114 42.13 -72.57
01301 11115 42.63 -72.59
01301 11116 42.63 -72.59")
CustomersZip <- fread("
Zip ID lat lng
01001 65484654805 42.07 -72.63
01001 64846124846 42.07 -72.63
01001 68421548945 42.07 -72.63
01001 84051545484 42.07 -72.63
01001 97545154848 42.07 -72.63
01002 64841515484 42.38 -72.52", colClasses = list(character="ID"))
关于r - 从 R 中的两个数据表中查找最接近的邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66066717/