Home > Mobile >  R create sf polyline from nested list of coordinates
R create sf polyline from nested list of coordinates

Time:05-14

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

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

Here is a tidyverse approach:

library(tidyverse)
  
map_dfr(feature$geometry$coordinates,
        ~ data.frame(.x)) %>%
  as.matrix() %>%
  st_linestring() %>%
  ggplot(.)  
  geom_sf(lwd = 3, lineend = "round")

Output

enter image description here

  •  Tags:  
  • r sf
  • Related