我有一个包含LINESTRING几何图形的大型sf-object(约100000行)。我想要更改每个linestring的第一个和最后一个坐标/点。
我知道可以通过将linestrings转换为points来实现此目的,更改每个linestring id的第一行/点和最后一行/点的几何图形,然后再将其转换回linestring。但这似乎需要很多额外的(不必要的?)步骤和计算。我有一种感觉,这可以用更直接的方式完成...但我不知道如何做。
library(sf)
library(tidyverse)
#sample data
mypoints <- data.frame(id = 1, lon = 1:5, lat = 1:5)
line1 <- mypoints %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
dplyr::group_by(id) %>%
dplyr::summarise() %>%
st_cast("LINESTRING")
# desired output
# change first coordinate of line from (1,1) to (1,2),
# and last coordinate from (5,5) to (5,4)
# so in the end, line 1 should look like line2
mypoints2 <- data.frame(id = 1, lon = c(1:5), lat = c(2,2:4,4))
line2 <- mypoints2 %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
dplyr::group_by(id) %>%
dplyr::summarise() %>%
st_cast("LINESTRING")
# old = blue, new = red
ggplot() +
geom_sf(data = line1, color = "blue", linewidth = 6) +
geom_sf(data = line2, color = "red", linewidth = 3)
我的当前方法:
# cast LINESTRINGs to POINTs
line2 <- line1 %>% st_cast("POINT")
# create sf object with net start ans endpoints
new_start_end <- data.frame(id = c("first", "last"),
lon = c(1,5),
lat = c(2,4)) %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326)
# set first and last value of geometry to new values
st_geometry(line2[c(1,nrow(line2)),]) <- st_geometry(new_start_end)
line2 %>%
dplyr::group_by(id) %>%
dplyr::summarise() %>%
st_cast("LINESTRING")
# Simple feature collection with 1 feature and 1 field
# Geometry type: LINESTRING
# Dimension: XY
# Bounding box: xmin: 1 ymin: 2 xmax: 5 ymax: 4
# Geodetic CRS: WGS 84
# # A tibble: 1 × 2
# id geometry
# <dbl> <LINESTRING [°]>
# 1 1 (1 2, 2 2, 3 3, 4 4, 5 4)