首页 > 解决方案 > 跨多个数据帧的 lat long 之间的最小距离

问题描述

我有一个名为 A 的数据框,它在单独的列中有纬度和经度。样本数据

ID   Lat          Long    
a          10.773046   76.6392061   
b          10.7751978  76.6368363 
c          12.954027   78.988818 
d          12.9608638  77.521573 

我有一个名为 Test 的数据框,它在单独的列中有 lat long。样本数据

Store   Lat          Long    
a          21.244769   81.63861
b          9.919337    78.14844
c          10.053961   76.32757
d          13.829922   77.49369
e          23.849729   77.93647

我想在每个 ID 上运行一个循环,以找到从他的 lat long 和 store 的 lat long 到最近的商店的最小距离。因此 ID a 将检查 a、b、c、d 和 e 并找到最近的商店。

目标 - 找到最小距离和商店名称。

输出应该告诉我

Id          Lat          Long       Store   Distance 
a          10.773046   76.6392061   b         50ms


a$Distance <- NA  # Make an "empty" variable in my data.frame

myFunction <- function(x, y){
  distm(c(lon1, lat1), c(lon2, lat2), fun = distHaversine)
}


for(ii in a){
  for(jj in Test){
    tempX <- a[a$Lat == ii & Store$Lat== jj, c("Lat")]
    tempY <- a[a$Long == ii & Store$Long == jj, c("Long")]
    # "Save" results into appropriate location in my data.frame
    myFunction(tempX,tempY)
  }
}

我无法获得确切的输出。

标签: r

解决方案


你可以看看这个

    a <- data.frame(ID = c("a", "b", "c", "d"),    Lat = c(10.773046, 10.7751978, 12.954027, 12.9608638), 
                Long = c(76.6392061, 76.6392061, 78.988818, 77.521573))    


b <- data.frame(Store = c("a", "b", "c", "d", "e"), Lat = c(21.244769,  9.919337, 10.053961, 13.829922, 23.849729), 
                Long = c(81.63861, 78.14844, 76.32757, 77.49369, 77.93647))

library(tidyverse)

earth.dist <- function (long1, lat1, long2, lat2)
{
  rad <- pi/180
  a1 <- lat1 * rad
  a2 <- long1 * rad
  b1 <- lat2 * rad
  b2 <- long2 * rad
  dlon <- b2 - a2
  dlat <- b1 - a1
  a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
  c <- 2 * atan2(sqrt(a), sqrt(1 - a))
  R <- 6378.145
  d <- R * c
  return(d)
}


a1 <- a %>%
  group_by(ID, Lat, Long) %>%
  summarise(closest = which.min(abs(Lat - b$Lat) + abs(Long - b$Long))) %>%
  mutate(Store  = b$Store[closest],
         Distance = sqrt((Lat - b$Lat[closest])^2 + (Long - b$Long[closest])^2), 
         distKm = earth.dist(Lat, Long, b$Lat[closest],b$Long[closest]))

结果是:

a1
  ID      Lat  Long closest Store Distance distKm
  <fct> <dbl> <dbl>   <int> <fct>    <dbl>  <dbl>
1 a      10.8  76.6       3 c        0.784   39.4
2 b      10.8  76.6       3 c        0.786   39.4
3 c      13.0  79.0       4 d        1.73   168. 
4 d      13.0  77.5       4 d        0.870   21.2

推荐阅读