R中的最短距离 [英] Shortest distance in R

查看:49
本文介绍了R中的最短距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何为下面的代码计算两个属性(点)之间的最短距离.有两个 shapefile 文件,一个是点 shapefile,另一个是道路 shapefile.

为了测试,可以从以下网站下载两个 shapefile:

示例

解决方案

您只需使用 st_distance 即可获得距离矩阵并找到最小值.我编写了一个函数,可以处理所有这些并返回一个新的 sf data.frame.data.frame 将包含名为 nearestdistance 的属性,它们分别是最近点的索引和到该点的距离.请注意,距离以米为单位反映您的投影.您的数据具有重复点,因此某些点因此没有显示距离.如果您不想要这些点,则必须删除重复项.

getNearest <- function(shp){dist <- as.data.frame(st_distance(shp))for (i in 1:ncol(dist)){行 <- seq(1:ncol(dist))行 <- 行 [i != 行]shp[i, '最近的'] <- which.min(dist[rows, i])shp[i, '距离'] <- dist[which.min(dist[rows, i]), i]}退货(shp)}pts2 <- getNearest(pts)

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

解决方案

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)

这篇关于R中的最短距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆