gpt4 book ai didi

r - 应该很容易 : distance along a line in R?

转载 作者:行者123 更新时间:2023-12-04 12:51:20 25 4
gpt4 key购买 nike

我在莫桑比克有一个铁路的 Shapefile,并使用下面的代码在铁路上生成了 100 个随机点。

我的问题很简单,但我找不到答案:你如何计算铁路沿线点之间的距离?

我不想要欧几里得距离,我想要沿着铁轨从 A 点到 B 点的距离。

提前致谢!

library(sp)
library(rgdal)
library(spgrass6)
library(maptools)
library(igraph)
library(fields)

railroads <- readShapeLines("MOZ_rails.shp")

#Generate 100 random points, and put them on a matrix:
RandomPoints<-spsample(railroads, 100, type="random")

最佳答案

可以使用 stplanr 包计算路由网络上的最短路径。我在荷兰的整个铁路网络中使用了一个 shapefile。此 shapefile 可从以下位置获得:
https://mapcruzin.com/free-netherlands-arcgis-maps-shapefiles.htm

library(sf)
library(ggplot2)
library(stplanr)

# Read shapefile
nl_rails_sf <- sf::st_read("~/netherlands-railways-shape/railways.shp")

# Generate 100 random points
set.seed(12345)
RandomPoints <- sf::st_sample(nl_rails_sf, 100, type = "random", exact = TRUE)
X <- st_coordinates(RandomPoints)[,1]
Y <- st_coordinates(RandomPoints)[,2]

# Find shortest route
slnetwork <- SpatialLinesNetwork(nl_rails_sf)
find_nodes <- find_network_nodes(sln = slnetwork, x = X, y = Y, maxdist = 2e6)
route_dhdb_df <- expand.grid(start = find_nodes, end = find_nodes) %>%
mutate(id_route = 1:nrow(.))
route_dhdb_sf <- sum_network_links(sln = slnetwork, routedata = route_dhdb_df)

# Route length
route_dhdb_sf %>%
group_by(id_route) %>%
summarize(length = sum(length))

# Plot results
ggplot(nl_rails_sf) +
geom_sf() +
theme_void() +
geom_sf(data = RandomPoints, color = "red") +
geom_sf(data = route_dhdb_sf, color = "red")
enter image description here

关于r - 应该很容易 : distance along a line in R?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28922874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com