我想从每一条路线中得到最近的位置和从路线到那个地方的距离。我想我可以通过SF做这件事,但我不知道怎么做。在样本数据中有19条不同的路线。
install.packages("sf")
install.packages("sfheaders")
library(sf)
routeData <- read.csv("https://www.dropbox.com/s/vtj8wvcqxj52pbl/SpainActivityRoutes.csv?dl=1")
# Convert routes to SF
sfheaders::sf_multipolygon(
obj = spainActivityRoutes
, multipolygon_id = "id"
, x = "lon"
, y = "lat"
)
# Read in locations
locations <- data.frame(id = c(1,2,3),
place = c('Alcudia', 'Puerto de Pollensa', 'Alaro'),
latitude = c(39.85327712, 39.9024565, 39.704459175469395),
longitude = c(3.123974802, 3.080426926, 2.7919874776545694))发布于 2022-08-26 11:00:11
从数据开始:
routeData <- read.csv("https://www.dropbox.com/s/vtj8wvcqxj52pbl/SpainActivityRoutes.csv?dl=1")拆分id,应用函数创建行字符串对象,使用st_sfc连接行字符串列表以生成空间向量。假设这些是EPSG代码4326的"GPS“坐标:
routes = do.call(st_sfc, lapply(split(routeData, routeData$id) , function(d){st_linestring(cbind(d$lon, d$lat))}))
st_crs(routes)=4326将点数据帧转换为具有相同坐标系的空间点数据帧:
pts = st_as_sf(locations, coords=c("longitude","latitude"), crs=4326)现在,我们可以得到最近的路线到每一个点:
> nearf = st_nearest_feature(pts, routes)
> nearf
[1] 1 15 19因此,第一个点最接近路线1,第二个点路线15,第三个点路线19。现在,通过使用st_distance和by_element=TRUE计算从每个点依次到每条路线线的距离,我们得到的距离(否则它将所有点到所有三个路线的距离作为一个矩阵计算):
> st_distance(pts, routes[st_nearest_feature(pts, routes)], by_element=TRUE)
Units: [m]
[1] 7.888465 27.046029 44.175458如果您希望路径上的点离点数据最近,那么使用st_nearest_points和pairwise=TRUE
> st_nearest_points(pts, routes[st_nearest_feature(pts, routes)], pairwise=TRUE)
Geometry set for 3 features
Geometry type: LINESTRING
Dimension: XY
Bounding box: xmin: 2.791987 ymin: 39.70412 xmax: 3.124058 ymax: 39.90256
Geodetic CRS: WGS 84
LINESTRING (3.123975 39.85328, 3.124058 39.85331)
LINESTRING (3.080427 39.90246, 3.080143 39.90256)
LINESTRING (2.791987 39.70446, 2.792247 39.70412)它从测试点返回到行的两点行。您可以使用像st_cast(...,"POINT")这样的函数将这些点分割成点,并将位置作为点。
https://stackoverflow.com/questions/73492435
复制相似问题