r - 如何在 sf 对象的列表列上使用 unnest?
问题描述
我有一个由 sf 对象组成的列表列的小标题。这些 sf 对象中的每一个都有一个或多个多边形行。类似于我如何取消嵌套 tibbles 列表,我希望取消嵌套 sf 对象。
数据看起来像这样
library(sf)
library(tibble)
poly <- st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))
a = st_sf(st_sfc(poly,poly))
b = st_sf(st_sfc(poly,poly))
df <- tibble(name=c('a','b'),poly=list(a,b))
我希望结果是一个看起来像这样的 sf 对象:
|name | geometry |
|-----|----------|
|a | POLYGON |
|a | POLYGON |
|b | POLYGON |
|b | POLYGON |
但是,当我使用 unnest 时,我收到一个错误,并且由于某种原因无法找到 unnest.sf。
编辑:我正在使用 sf 版本 0.7-4
谢谢!
本
解决方案
按照新的术语,它会unchop()
超过unnest()
. 这是一种方法:
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
poly <- st_polygon(list(cbind(c(0,3,3,0,0),c(0,0,3,3,0))))
a = st_sf(st_sfc(poly,poly))
b = st_sf(st_sfc(poly,poly))
df <- tibble(name=c('a','b'),poly=list(a,b))
unchop_poly <- function(data, col) {
mutate(data, {{col}} := map({{col}}, ~split(., seq_len(nrow(.))))) %>%
unchop({{col}})
}
df2 <- df %>%
unchop_poly(poly)
df2
#> # A tibble: 4 x 2
#> name poly
#> <chr> <list>
#> 1 a <df[,1] [1 x 1]>
#> 2 a <df[,1] [1 x 1]>
#> 3 b <df[,1] [1 x 1]>
#> 4 b <df[,1] [1 x 1]>
df2$poly
#> [[1]]
#> Simple feature collection with 1 feature and 0 fields
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 0 ymin: 0 xmax: 3 ymax: 3
#> epsg (SRID): NA
#> proj4string: NA
#> st_sfc.poly..poly.
#> 1 POLYGON ((0 0, 3 0, 3 3, 0 ...
#>
#> [[2]]
#> Simple feature collection with 1 feature and 0 fields
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 0 ymin: 0 xmax: 3 ymax: 3
#> epsg (SRID): NA
#> proj4string: NA
#> st_sfc.poly..poly.
#> 1 POLYGON ((0 0, 3 0, 3 3, 0 ...
#>
#> [[3]]
#> Simple feature collection with 1 feature and 0 fields
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 0 ymin: 0 xmax: 3 ymax: 3
#> epsg (SRID): NA
#> proj4string: NA
#> st_sfc.poly..poly.
#> 1 POLYGON ((0 0, 3 0, 3 3, 0 ...
#>
#> [[4]]
#> Simple feature collection with 1 feature and 0 fields
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 0 ymin: 0 xmax: 3 ymax: 3
#> epsg (SRID): NA
#> proj4string: NA
#> st_sfc.poly..poly.
#> 1 POLYGON ((0 0, 3 0, 3 3, 0 ...
由reprex 包(v0.3.0)于 2019 年 9 月 19 日创建
推荐阅读
- android - 如何在另一个应用程序上显示自定义对话
- vue.js - Vue组合api - 组件在开始使用reactive()时不呈现
- c# - 为什么 CMake 不能成功设置 COMMON_LANGUAGE_RUNTIME
- ios - ios 14,webp 动画在 safari 和 chrome 中以白色背景闪烁
- java - Dropwizard DropwizardAppRule 测试分段文件上传
- mysql - 在 SQL 表中查找重复值并在列中添加唯一值
- postgresql - 如何修改添加类型枚举表postgres?
- go - 我可以将 Google 表格读取为 CSV 文件吗
- javascript - Firebase Web JS,在后台接收通知,然后在您的网页中处理它
- python - 可以在 django 的 db 中保存查询集吗?