[英]Shortest distance in R
我想知道如何為下面的代碼計算兩個屬性(點)之間的最短距離。 有兩個 shapefile 文件,一個是點 shapefile,另一個是道路 shapefile。
為了進行測試,可以從以下網站下載兩個 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)
您可以使用st_distance
來獲取距離矩陣並找到最小值。 我寫了一個 function 可以處理所有這些並返回一個新的sf
data.frame。 data.frame 將包含稱為nearest
和distance
的屬性,它們分別是最近點的索引和到該點的距離。 請注意,距離以米為單位,反映您的投影。 您的數據有重復點,因此有些點沒有顯示距離。 如果您不想要這些點,則必須刪除重復項。
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)
據我了解,您正在嘗試測量沿路到每個點的距離以及它的最近點。 請在此處查看類似的工作流程: https://community.rstudio.com/t/distance-between-points-along-network-path/49596/2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.