问题描述
我正在尝试提取将坐标信息保存到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
解决方法
您的列表有两个问题,它们会引发flatten_dfr
错误。
- 并非所有嵌套列表都被命名。
coordinates
中的两个列表都需要名称。 - 您使用列表名称
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
列表看起来像是使用geojson
之类的内容来读取jsonlite::fromJSON()
的结果。
如果您直接使用geojson
阅读sf::st_read()
,则会得到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...