【问题标题】:Purrr flatten_dfr咕噜 flatten_dfr
【发布时间】:2021-01-19 06:11:48
【问题描述】:

我正在尝试将保存坐标信息的列表列表提取到 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 列(leaflet_id、feature_type、几何)的 sf 数据框

我尝试使用 purrr::flatten_dfr(feature) 但得到错误:参数 1 必须有名称。

我已经查看了类似下面的其他 SO 帖子,这些帖子看起来很有希望但没有奏效。

谢谢

Error in bind_rows_(x, .id) : Argument 1 must have names

【问题讨论】:

  • 您的预期输出如何查找共享的数据?

标签: r purrr sf


【解决方案1】:

您的feature 列表看起来像是使用jsonlite::fromJSON() 之类的内容读取geojson 的结果。

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

要按原样修复代码,您可以这样做

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...

【讨论】:

    【解决方案2】:

    您的列表有两个问题会引发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]>  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多