简体   繁体   English

R 中的最短距离

[英]Shortest distance in R

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.有两个 shapefile 文件,一个是点 shapefile,另一个是道路 shapefile。

For testing, both shapefiles can be downloaded from the following website: https://github.com/JovaniSouza/JovaniSouza5/blob/master/Example.zip为了进行测试,可以从以下网站下载两个 shapefile: 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例子

在此处输入图像描述

You can just use st_distance to get a distance matrix and find the minimum.您可以使用st_distance来获取距离矩阵并找到最小值。 I wrote a function that can process all of that and return a new sf data.frame.我写了一个 function 可以处理所有这些并返回一个新的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. data.frame 将包含称为nearestdistance的属性,它们分别是最近点的索引和到该点的距离。 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)

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://community.rstudio.com/t/distance-between-points-along-network-path/49596/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM