Shortest distance in R

有些话、适合烂在心里 提交于 2020-07-15 09:40:47

问题


I would like to know how to calculate the shortest distance between two properties (points) for my code below. There are two shapefile files, one being a points shapefile, the other a roads shapefile.

For testing, both shapefiles can be downloaded from the following website: https://github.com/JovaniSouza/JovaniSouza5/blob/master/Example.zip

library(sf)

roads <- st_read('Roads/Roads.shp')
pts <- st_read('Points/Points.shp') %>% 
  st_transform(crs=st_crs(roads))


plot(st_geometry(roads))
plot(st_geometry(pts), add = T, col = 'red', pch = 20)

Example


回答1:


You can just use st_distance to get a distance matrix and find the minimum. I wrote a function that can process all of that and return a new sf data.frame. The data.frame will contain attributes called nearest and distance which is the index of the nearest point and the distance to that point respectively. Note the distances are in meters reflecting your projection. Your data have repeating points, so some of the points show no distance because of that. If you don't want those points you will have to remove the duplicates.

getNearest <- function(shp){
  dist <- as.data.frame(st_distance(shp))
  for (i in 1:ncol(dist)){
    rows <- seq(1:ncol(dist))
    rows <- rows[i != rows]
    shp[i, 'nearest'] <- which.min(dist[rows, i])
    shp[i, 'distance'] <- dist[which.min(dist[rows, i]), i]
  }
  return(shp)
}

pts2 <- getNearest(pts)



回答2:


From what I understand, you are trying to measure the distance along the road to each point and it's closest point. Please see a similar workflow here: https://community.rstudio.com/t/distance-between-points-along-network-path/49596/2



来源:https://stackoverflow.com/questions/62662368/shortest-distance-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!