呼噜声 flatten_dfr

Purrr flatten_dfr

我正在尝试将包含坐标信息的列表列表提取到 sf 数据框中。

这是名单

feature <- list(type = "Feature", properties = list(`_leaflet_id` = 26065L, 
feature_type = "polyline"), geometry = list(type = "LineString", 
coordinates = list(list(-74.210091, 40.382121), list(-73.942375, 
    40.661889))))

我想将其转换为 3 列的 sf 数据框(leaflet_id、feature_type、几何)

我试过使用 purrr::flatten_dfr(功能),但出现错误:参数 1 必须有名称。

我已经查看了像下面这样的其他 SO 帖子,这些帖子看起来很有前途但没有用。

谢谢

您的列表有两个问题会引发 flatten_dfr 错误。

  1. 并非所有嵌套列表都已命名。 coordinates 中的两个列表需要名称。
  2. 您使用列表名称 type 两次。这行不通,因为 flatten 之后的数据框将有两列同名。

如果您解决了这些问题,flatten_dfr 将 运行 没有错误:

feature <- list(type = "Feature", 
                properties = list(`_leaflet_id` = 26065L, 
                                  feature_type = "polyline"), 
                geometry = list(type1 = "LineString", 
                                coordinates = list(foo=list(-74.210091, 40.382121), 
                                                   bar=list(-73.942375, 
 
flatten_dfr(feature)
# A tibble: 2 x 5
  type    `_leaflet_id` feature_type type1      coordinates 
  <chr>           <int> <chr>        <chr>      <named list>
1 Feature         26065 polyline     LineString <list [2]>  
2 Feature         26065 polyline     LineString <list [2]>  

您的 feature 列表看起来像是使用 jsonlite::fromJSON().

之类的内容阅读 geojson 的结果

如果您直接使用 sf::st_read() 阅读 geojson,您将获得 sf 对象。

要修复您的代码 as-is,您可以这样做

library(jsonlite)
library(sf)

sf <- jsonlite::toJSON( feature, auto_unbox = TRUE ) %>%
    sf::st_read()

sf
# Simple feature collection with 1 feature and 2 fields
# geometry type:  LINESTRING
# dimension:      XY
# bbox:           xmin: -74.21009 ymin: 40.38212 xmax: -73.94238 ymax: 40.66189
# z_range:        zmin: NA zmax: NA
# m_range:        mmin: NA mmax: NA
# geographic CRS: WGS 84
# _leaflet_id feature_type                       geometry
# 1       26065     polyline LINESTRING (-74.21009 40.38...