'How summarize points to linestring and keep dataframe columns in r?
I'm working with this code to turn a group of points into lines. But, in addition to the "sub_id" the rows have another "id" (column in input dataframe) that I would like to be kept in the final object. How can I do this?
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") %>%
Solution 1:[1]
It's hard to say from just this code snippet, but it might work adding the other id to the group_by step:
df.line <- df.sf %>%
dplyr::group_by(sub_id, id) %>%
dplyr::summarize() %>%
sf::st_cast("LINESTRING")
Solution 2:[2]
library(sfheaders) is designed for this exact 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...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aron |
| Solution 2 | SymbolixAU |
