有没有更有效的方法来测量<LINESTRING>
或<MULTILINESTRING>
的累积长度?换句话说,我需要测量从起点到终点的点之间的距离.目前,我只想出了一个 idea ,将这<LINESTRING>
个部分分成单独的部分,并测量每一个部分的长度.这是可行的,但由于迭代方法,它需要花费大量时间.是否存在任何内置方法?
下面是我想出来的一份复印件.它以公元spData
年的塞纳河为例.尽管下面的示例使用了sf
和geos
包,但我很高兴听到像terra
、geos
甚至rsgeo
这样的其他空间包.
干杯!
library(sf)
#> Linking to GEOS 3.10.2, GDAL 3.4.1, PROJ 8.2.1; sf_use_s2() is TRUE
library(geos)
library(spData)
#> To access larger datasets in this package, install the spDataLarge
#> package with: `install.packages('spDataLarge',
#> repos='https://nowosad.github.io/drat/', type='source')`
# Example
lines <- seine[2, ]
# My foo
cumulative_length <-
function(input) {
# Save CRS
crs <- sf::st_crs(input)
# Retrive coordinates
lines_coo <-
sf::st_coordinates(input)
# Count number of segments of linestring
n <- nrow(lines_coo) - 1
# Pre-allocate a list
lines_geos <-
vector(mode = "list", length = n)
# Construct linestrings
for (i in 1:n) {
lines_geos[[i]] <-
geos::geos_make_linestring(lines_coo[i:(i+1),1],
lines_coo[i:(i+1),2],
crs = crs)
}
# Measure cumulative segment length
lines_order <-
sapply(lines_geos, geos::geos_length) |>
append(0, 0) |>
cumsum()
return(lines_order)
}
bench::mark(cumulative_length(lines))
#> # A tibble: 1 × 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 cumulative_length(lines) 13ms 13.7ms 72.9 244KB 109.
创建于2024-03-23,共reprex v2.0.2个
UPDATE
期望的输出正好如下所示,即长度从0
到st_length(lines)
的单调递增的数字向量:
cumulative_length(lines) |>
head()
#> [1] 0.000 1716.196 3290.379 4824.087 6745.759 7446.660