'R create sf polyline from nested list of coordinates

I have a nested list of coordinates in the following format:

feature <- list(type = "Feature", properties = list(`_leaflet_id` = 125L, 
    feature_type = "polyline"), geometry = list(type = "LineString", 
    coordinates = list(list(-176.264648, 59.355596), list(-165.541992, 
        60.951777), list(-158.510742, 57.891497))))

I am trying to convert this to a simple feature sf layer by unpacking the the nested list coordinates into a geometry.

I've tried the following experiments, trying to just make a dataframe of coords first, but none seem to work.

xs <- as.data.frame(feature) 
xs <- bind_rows(feature[["geometry"]][["coordinates"]])
xs <- feature[["geometry"]] %>% set_names() %>% bind_rows() 

Is there a straightforward way to do this?

Note: the number of coordinate pairs (vertices on the line) is arbitrary may change

rsf


Solution 1:[1]

Your feature looks like the result of converting geojson into an R object

If you have access to the geojson object before it is converted into your feature, then you can ignore the to_json() step(s) here

library(sf)

## convert back to JSON

### Option 1
js <- jsonify::to_json(feature, unbox = TRUE)

### Option 2
js <- jsonlite::toJSON(feature, auto_unbox = TRUE)

## Then you can convert to SF

### Option 1
geojsonsf::geojson_sf(js)

### Option 2
sf::st_read(js)

Solution 2:[2]

If you unlist it, and put it into a matrix, the st_linestring from the sf package can then use it.

coords <- matrix(unlist(feature$geometry$coordinates), byrow = TRUE, ncol = 2)

linestring <- st_linestring(coords)

plot(linestring)

Solution 3:[3]

Here is a tidyverse approach:

library(tidyverse)
library(sf)
  
map_dfr(feature$geometry$coordinates,
        ~ data.frame(.x) %>% set_names(c("x", "y"))) %>%
  as.matrix() %>%
  st_linestring() %>%
  st_sfc(crs = 4326) %>%
  st_as_sf() %>%
  ggplot() +
  geom_sf(lwd = 3, lineend = "round")

Output

enter image description here

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
Solution 2 Jahi Zamy
Solution 3