有一个名为“zip code”的方便的r包,它提供了一个包含邮政编码、城市、州和经度的表。所以一旦你有了这些信息,“地球圈”软件包就可以计算出点之间的距离。
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"]))
})
关于输入数据帧的列类的警告。邮政编码应该是一个字符而不是数字,否则前导零会被删除,从而导致错误。
距离distgeo的返回距离以米为单位,我将允许读者确定正确的单位转换为英里。