如何总结指向线串并在 r 中保留数据框列?

How summarize points to linestring and keep dataframe columns in r?

我正在使用这段代码将一组点变成线。但是,除了“sub_id”之外,这些行还有另一个“id”(输入数据框中的列),我希望将其保留在最终对象中。我该怎么做?

library(tidyverse)
library(sf)

id <- c("844", "844", "844", "844", "844","844", "844", "844", "844", "844",
        "844", "844", "845", "845", "845", "845", "845","845", "845", "845", 
        "845","845", "845", "845")
sub_ids <- c("2017_844_1", "2017_844_1", "2017_844_1", "2017_844_1", "2017_844_2",
        "2017_844_2", "2017_844_2", "2017_844_2", "2017_844_3", "2017_844_3",
        "2017_844_3", "2017_844_3", "2017_845_1", "2017_845_1", "2017_845_1", 
        "2017_845_1", "2017_845_2","2017_845_2", "2017_845_2", "2017_845_2", 
        "2017_845_3","2017_845_3", "2017_845_3", "2017_845_3")
lat <- c(-30.6456, -29.5648, -27.6667, -31.5587, -30.6934, -29.3147, -23.0538, 
         -26.5877, -26.6923, -23.40865, -23.1143, -23.28331, -31.6456, -24.5648, 
         -27.6867, -31.4587, -30.6784, -28.3447, -23.0466, -27.5877, -26.8524, 
         -23.8855, -24.1143, -23.5874)
long <- c(-50.4879, -49.8715, -51.8716, -50.4456, -50.9842, -51.9787, -41.2343, 
          -40.2859, -40.19599, -41.64302, -41.58042, -41.55057, -50.4576, -48.8715, 
          -51.4566, -51.4456, -50.4477, -50.9937, -41.4789, -41.3859, -40.2536, 
          -41.6502, -40.5442, -41.4057)
df <- tibble(id, sub_ids, lat, long)


#converting ​to sf
df.sf <- df %>% 
 ​sf::st_as_sf(coords = c("long", "lat"), crs = 4326)

#creating linestrings
df.line <- df.sf %>% 
  dplyr::group_by(sub_ids) %>%
  dplyr::summarize() %>%
  sf::st_cast("LINESTRING") %>%

仅凭此代码片段很难判断,但将另一个 ID 添加到 group_by 步骤可能会奏效:

df.line <- df.sf %>% 
  dplyr::group_by(sub_id, id) %>%
  dplyr::summarize() %>%
  sf::st_cast("LINESTRING")

library(sfheaders) 正是为此而设计的 use-case

library(sfheaders)

sfheaders::sf_linestring(
  obj = df
  , x = "long"
  , y = "lat"
  , linestring_id = "sub_ids"
  , keep = T
)

# Simple feature collection with 6 features and 2 fields
# Geometry type: LINESTRING
# Dimension:     XY
# Bounding box:  xmin: -51.9787 ymin: -31.6456 xmax: -40.19599 ymax: -23.0466
# CRS:           NA
#      sub_ids sub_ids                       geometry
# 1 2017_844_1     844 LINESTRING (-50.4879 -30.64...
# 2 2017_844_2     844 LINESTRING (-50.9842 -30.69...
# 3 2017_844_3     844 LINESTRING (-40.19599 -26.6...
# 4 2017_845_1     845 LINESTRING (-50.4576 -31.64...
# 5 2017_845_2     845 LINESTRING (-50.4477 -30.67...
# 6 2017_845_3     845 LINESTRING (-40.2536 -26.85...