我有一个大的shapefile,需要按属性(分组值(将其拆分为多个。在ArcGIS中,此函数调用Split By Attribute
。让我们从sf
库中读取nc
数据帧作为示例
library(tidyverse)
library(sf)
nc = st_read(system.file("shape/nc.shp", package="sf"))
nc
Simple feature collection with 100 features and 14 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
epsg (SRID): 4267
proj4string: +proj=longlat +datum=NAD27 +no_defs
First 10 features:
AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID
1 0.114 1.442 1825 1825 Ashe 37009 37009 5
2 0.061 1.231 1827 1827 Alleghany 37005 37005 3
3 0.143 1.630 1828 1828 Surry 37171 37171 86
我想根据NAME
变量将其拆分为100个形状文件。所以我要像这样去group_by
,nest
和walk
。
nc %>%
mutate(group = as.character(NAME)) %>%
group_by(group) %>%
nest() %>%
mutate(data = map(data, ~st_as_sf(.x))) %>%
walk2(.x = data, .y = group,
~st_write(obj = .x,
dsn = paste0(.y,
".shp")))
这个漂亮的管道返回给我以下错误:
错误:无法将
grouped_df/tbl_df/tbl/data.frame
对象转换为函数
nc %>%
mutate(group = as.character(NAME)) %>%
group_by(group) %>%
nest() %>%
#move walk2 inside mutate as data and group were invisibale for walk2
#also no need for data you can ran walk2 directly
mutate(#data = map(data, ~st_as_sf(.x)),
txt = walk2(.x = data, .y = group, ~st_write(obj = .x, dsn = paste0(.y, ".shp"))))