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

标签 r group-by geometry sf summarize

我正在使用这段代码将一组点变成线。但是,除了“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") %>%

最佳答案

library(sfheaders) 正是为这个用例而设计的

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...

关于r - 如何总结指向线串并在 r 中保留数据框列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71914426/

相关文章:

r - Shiny 的 observeEvent() 中的执行顺序是什么?

mongodb - 仅在 MongoDB 中满足特定条件时分组

sql - 仅对某些列进行分组

测地球的数学

algorithm - 我如何知道多边形的内部是位于顶点的右侧还是左侧?

opencv - 使用 OCR 阅读循环文本

r - R 中的动物园 na.approx

r - 更改 `docker`示例脚本以在本地文件(R包)上运行

r - 在 R (ggplot) 中注释公式(使用 bqoute 或替代)给出错误

r - 如何将重复值分组为单个值并在 R 中提取与该列值关联的值?