简体   繁体   English

R从嵌套的坐标列表创建sf折线

[英]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.我试图通过将嵌套列表坐标解压缩到几何中来将其转换为简单的特征 sf 层。

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注意:坐标对(线上的顶点)的数量是任意的,可能会改变

Your feature looks like the result of converting geojson into an R object您的feature看起来像是将geojson转换为 R 对象的结果

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如果您在将 geojson 对象转换为您的feature之前可以访问它,那么您可以忽略此处的to_json()步骤

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)

If you unlist it, and put it into a matrix, the st_linestring from the sf package can then use it.如果将其取消列出并将其放入矩阵中,则 sf 包中的 st_linestring 可以使用它。

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

linestring <- st_linestring(coords)

plot(linestring)

Here is a tidyverse approach:这是一个tidyverse方法:

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输出

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM