测量沿R中一条线的所有点的距离(sf中的线串)

问题描述 投票:1回答:1

我有一个平滑的线(简化的海岸线抽象),这是一个linestring,我想沿着它频繁地测量线的长度。我可以创建平滑线,并测量其长度:

library(raster)
library(sf)
library(tidyverse)
library(rnaturalearth)
library(smoothr)

# create bounding box for the line 
xmin=-80
xmax=-66
ymin=24
ymax=45
bbox <- extent(xmin, xmax, ymin, ymax)

# get coarse outline of the US 
usamap <- rnaturalearth::ne_countries(scale = "small", country = "united states of america", returnclass = "sf")[1] %>% 
  st_cast("MULTILINESTRING")

# crop to extent of the bbox and get rid of a border line that isn't coastal 
bbox2 <- st_set_crs(st_as_sf(as(raster::extent(-80, -74, 42, 45.5), "SpatialPolygons")), st_crs(usamap))
cropmap <- usamap %>% 
  st_crop(bbox) %>% 
  st_difference(bbox2)

# smooth the line 
smoothmap <- cropmap %>% 
  smoothr::smooth(method="ksmooth", smoothness=8)

# measure the line length
st_length(smoothmap) # I get 1855956m

我将要沿着这条线“捕捉”样本点,我需要知道它们沿着海岸线走了多远。但是,我无法弄清楚如何沿着海岸线间隔测量线的长度。区间大小并不是非常重要,只要它的分辨率相对较高,可能每1公里或每0.01度。

我想要产生的是一个数据框,其中x,y列包含沿线的纬度/经度,以及一个“长度”列,其中包含沿线的距离(从原点到该点)。以下是我尝试过的一些事情:

迭代边界框。我尝试使用越来越小的边界框裁剪线(在lat / lon中使用常规间隔),但由于线在-76,38左右“向后”弯曲,因此一些裁剪框不包含我的完整线段预期。这种方法适用于行的右上半部分,但不适用于左下半部分 - 只返回零长度。

在实现更平滑之前裁剪范围,然后测量线。由于如果仅测量原始线的一段,更平滑的功能不会产生相同的形状,这实际上并不测量沿同一线的距离。

使用linestring获取st_coordinates的坐标,修剪一行(线上的一个点),并将剩余的坐标重新设计为linestring。这种方法不会产生单个linestring,而是产生一系列点(因为st_cast不知道如何再次连接它们),因此无法正常测量。

理想的是“编辑”smoothmap的几何体,一次删除一行坐标,重复测量线,并将终点坐标和线长写入数据帧。但是,我不确定是否可以编辑sf对象的坐标而不将其转换为数据帧。

r spatial sf
1个回答
1
投票

如果我理解你的问题,我认为你可以这样做:

x <- as(smoothmap, "Spatial")
g <- geom(x)
d <- pointDistance(g[-nrow(g), c("x", "y")], g[-1, c("x", "y")], lonlat=TRUE)
gg <- data.frame(g[, c('x','y')], seglength=c(d, 0))

gg$lengthfromhere <- rev(cumsum(rev(gg[,"seglength"])))

head(gg)

#          x        y seglength lengthfromhere
#1 -67.06494 45.00000 70850.765        1855956
#2 -67.74832 44.58805  2405.180        1785105
#3 -67.77221 44.57474  2490.175        1782700
#4 -67.79692 44.56095  2577.254        1780210
#5 -67.82248 44.54667  2666.340        1777633
#6 -67.84890 44.53189  2757.336        1774967

tail(gg)
#            x        y  seglength lengthfromhere
#539 -79.09383 33.34224   2580.481       111543.5
#540 -79.11531 33.32753   2542.557       108963.0
#541 -79.13648 33.31306   2512.564       106420.5
#542 -79.15739 33.29874   2479.949       103907.9
#543 -79.17802 33.28460 101427.939       101427.9
#544 -80.00000 32.68751      0.000            0.0
© www.soinside.com 2019 - 2024. All rights reserved.