将sf对象列表转换为一个sf

时间:2018-07-12 19:15:00

标签: r list data.table rbind sf

我有一个sf对象的列表,我想对其进行行绑定以创建单个sf对象。我正在寻找类似于data.table::rbindlist的函数,该函数可以有效地堆叠单个对象。

可复制示例的数据:

my_list <- structure(list(structure(list(idhex = 4L, geometry = structure(list(
            structure(c(664106.970004623, 6524137.38910266), class = c("XY", 
            "POINT", "sfg"))), class = c("sfc_POINT", "sfc"), precision = 0, bbox = structure(c(xmin = 664106.970004623, 
            ymin = 6524137.38910266, xmax = 664106.970004623, ymax = 6524137.38910266
            ), class = "bbox"), crs = structure(list(epsg = 32633L, proj4string = "+proj=utm +zone=33 +datum=WGS84 +units=m +no_defs"), class = "crs"), n_empty = 0L)), row.names = 1L, class = c("sf", 
            "data.frame"), sf_column = "geometry", agr = structure(c(idhex = NA_integer_), .Label = c("constant", 
            "aggregate", "identity"), class = "factor")), structure(list(
            idhex = 9, geometry = structure(list(structure(c(665491.220375992, 
            6525002.7560692), class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT", 
            "sfc"), precision = 0, bbox = structure(c(xmin = 665491.220375992, 
            ymin = 6525002.7560692, xmax = 665491.220375992, ymax = 6525002.7560692
            ), class = "bbox"), crs = structure(list(epsg = 32633L, proj4string = "+proj=utm +zone=33 +datum=WGS84 +units=m +no_defs"), class = "crs"), n_empty = 0L)), row.names = 1L, class = c("sf", 
            "data.frame"), sf_column = "geometry", agr = structure(c(idhex = NA_integer_), .Label = c("constant", 
            "aggregate", "identity"), class = "factor"))), .Dim = 1:2, .Dimnames = list(
            ".", NULL))

请注意,data.tablesf库尚未完全兼容。因此,rbindlist函数返回一个未被识别为`sf对象的对象。

single_sf <- rbindlist(my_list)
class(single_sf)

2 个答案:

答案 0 :(得分:4)

df <- do.call(rbind, my_list)

> class(df)
[1] "sf"         "data.frame"

值得注意的是dplyr::bind_rowspurrr::map_dfr不适用于sf对象,因此在这种情况下rbind更好。

答案 1 :(得分:1)

这是一个老问题,但值得注意的是,最新版本的 dplyr (> 0.9) 可以绑定 sf 对象的行(在列表中与否):

single_sf <- dplyr::bind_rows(my_list)
class(single_sf)
[1] "sf"         "data.frame"

其他包也提供了可用于绑定 sf 对象的选项(例如 mapedit:::combine_list_of_sf()sf:::rbind.sfdata.table::rbindlist),除了上面提到的 do.call() 选项(有关讨论和一些基准测试,请参阅 https://github.com/r-spatial/sf/issues/798#)。但是 dplyr 选项也适用于 sf 对象,其数据框包含不同数量的列,这是 do.call()sf:::rbind.sf()data.table::rbindlist() 不能做的,并且对我处理具有不同列数的 sf 对象列表很重要。