我的数据集如下-

a
Location   loc.Lon   loc.Lat  Pincode      pin.lon     pin.lat
SPM        79.94533 12.97025 "602105"   79.95285     12.96752
SPM        79.94533 12.97025 "602106"   79.88568     12.91943


我想使用包ggmap计算两个密码的(loc.Lon,loc.Lat)和(pin.lon,pin.lat)之间的距离。

当我运行以下代码时,我得到了预期的结果-

mapdist(c(a$loc.Lon[2], a$loc.Lat[2]), c(a$pin.lon[2],a$pin.lat[2]), mode = "driving")


但是当我对整个数据集a执行以下查询时,出现错误-

a$dist = mapdist(c(a$loc.Lon, a$loc.Lat), c(a$pin.lon,a$pin.lat), mode = "driving")


我得到的错误是-

Error: is.character(from) is not TRUE


请帮助我进行排序。

最佳答案

mapdist接受fromto参数的向量,因此您可以转换它们并将此函数应用于数据集的每一行。

假设您想要公里的距离:

get_km_from_mapdist <- function(i) {
  mapdist(as.numeric(a[i, c('loc.Lon','loc.Lat')]),
          as.numeric(a[i, c('pin.lon','pin.lat')]),
          mode='driving')$km
}

a$dists = sapply(1:nrow(a), get_km_from_mapdist)

关于r - 如何使用R计算多个lon lat向量之间的距离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36616308/

10-12 17:15