首页 > 解决方案 > R按邮政编码接近合并2个data.frames

问题描述

我有 2 个带有邮政编码的 data.frames。一个是房屋,另一个是气象站。我需要通过邮政编码的接近度合并 2 个 data.frames,因此我将气象站的温度数据与离它最近的房屋合并。我无法按邮政编码的数量进行合并,因为它在 2 个 datas.frames 上并不相同,因为有些房屋在同一邮政编码中没有气象站。

这在R中可能吗?

非常感谢。

标签: rgeocoding

解决方案


这是基于气象站列表很小,因此不会影响计算时间的假设:

library(dplyr)
library(purrr)

df_with_homes_stats = df_with_homes %>% 
  dplyr::mutate(closestZip = purrr::map_dbl(.x=homeZip,~df_with_stats$stationZip[which.min(abs(.x-df_with_stats$stationZip))])) %>% 
  dplyr::left_join(df_with_stats,by=c('closestZip'='stationZip'))

这里,“df_with_homes”是包含每个家庭邮政编码的大型数据集,“df_with_stats”对应于车站的邮政编码。这里的基本假设是邮政编码之间的距离与它们之间的数学差异成正比。

让我知道它是否有效。


推荐阅读