我有一个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.table
和sf
库尚未完全兼容。因此,rbindlist
函数返回一个未被识别为`sf对象的对象。
single_sf <- rbindlist(my_list)
class(single_sf)
答案 0 :(得分:4)
df <- do.call(rbind, my_list)
> class(df)
[1] "sf" "data.frame"
值得注意的是dplyr::bind_rows
和purrr::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.sf
和 data.table::rbindlist
),除了上面提到的 do.call()
选项(有关讨论和一些基准测试,请参阅 https://github.com/r-spatial/sf/issues/798#)。但是 dplyr
选项也适用于 sf
对象,其数据框包含不同数量的列,这是 do.call()
、sf:::rbind.sf()
和 data.table::rbindlist()
不能做的,并且对我处理具有不同列数的 sf
对象列表很重要。