首页 > 解决方案 > 如何在 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

谢谢!

标签: rtidyrsf

解决方案


按照新的术语,它会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 日创建


推荐阅读