【问题标题】:How to calculate distance between multiple lon lat vectors using R如何使用 R 计算多个 lon lat 向量之间的距离
【发布时间】:2016-08-05 14:32:59
【问题描述】:

我的数据集如下-

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

请帮我整理一下。

【问题讨论】:

    标签: r ggmap


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

      as.character()paste0() 直接调用到您的数据上时,将坐标转换为字符串。

      a$dist_km <- mapdist(from = paste0(as.character(a$loc.Lat),",",as.character(a$loc.Lon)),
                           to = paste0(as.character(a$pin.Lat),", ",as.character(a$pin.Lon)))[,c('km')]
      

      【讨论】:

        猜你喜欢
        • 2012-04-04
        • 2013-01-26
        • 1970-01-01
        • 2018-08-07
        • 2016-06-15
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多