R 查找两个美国邮政编码列之间的距离

mrs*_*uid 2 r distance tidyverse geosphere

我想知道使用 R 计算两个美国邮政编码列之间的距离的最有效方法是什么。

我听说过用于计算邮政编码之间差异的 geosphere 包,但并不完全理解它,并且想知道是否还有其他方法。

例如说我有一个看起来像这样的数据框。

 ZIP_START     ZIP_END
 95051         98053
 94534         94128
 60193         60666
 94591         73344
 94128         94128
 94015         73344
 94553         94128
 10994         7105
 95008         94128
Run Code Online (Sandbox Code Playgroud)

我想创建一个看起来像这样的新数据框。

 ZIP_START     ZIP_END     MILES_DIFFERENCE
 95051         98053       x
 94534         94128       x
 60193         60666       x
 94591         73344       x
 94128         94128       x
 94015         73344       x
 94553         94128       x
 10994         7105        x
 95008         94128       x
Run Code Online (Sandbox Code Playgroud)

其中 x 是两个邮政编码之间的英里差。

计算此距离的最佳方法是什么?

这是创建示例数据框的 R 代码。

df <- data.frame("ZIP_START" = c(95051, 94534, 60193, 94591, 94128, 94015, 94553, 10994, 95008), "ZIP_END" = c(98053, 94128, 60666, 73344, 94128, 73344, 94128, 7105, 94128))
Run Code Online (Sandbox Code Playgroud)

请让我知道,如果你有任何问题。

任何建议表示赞赏。

感谢您的帮助。

Dav*_*e2e 8

有一个名为“zipcode”的方便的 R 包,它提供了一个包含邮政编码、城市、州以及纬度和经度的表格。所以一旦你有了这些信息,“geosphere”包就可以计算点之间的距离。

library(zipcode)
library(geosphere)

#dataframe need to be character arrays or the else the leading zeros will be dropped causing errors
df <- data.frame("ZIP_START" = c(95051, 94534, 60193, 94591, 94128, 94015, 94553, 10994, 95008), 
       "ZIP_END" = c(98053, 94128, 60666, 73344, 94128, 73344, 94128, "07105", 94128), 
       stringsAsFactors = FALSE)

data("zipcode")

df$distance_meters<-apply(df, 1, function(x){
  startindex<-which(x[["ZIP_START"]]==zipcode$zip)
  endindex<-which(x[["ZIP_END"]]==zipcode$zip)
  distGeo(p1=c(zipcode[startindex, "longitude"], zipcode[startindex, "latitude"]), p2=c(zipcode[endindex, "longitude"], zipcode[endindex, "latitude"]))
})
Run Code Online (Sandbox Code Playgroud)

关于输入数据框的列类的警告。邮政编码应该是字符而不是数字,否则会丢弃前导零导致错误。

从 distGeo 返回的距离以米为单位,我将允许读者确定正确的单位转换为英里。

更新
zipcode 包似乎已存档。有一个替换包:“zipcodeR”,它提供经度和纬度数据以及附加信息。