Merge a list of spatial polygon objects in R
To merge a list of Spatial objects, you can do:
library(raster)
m <- do.call(bind, buff.pts)
Given a list of SpatialPolygons
objects, here's how to construct a spatial polygons data frame with one feature per original SpatialPolygons
feature.
Sample data: spl
is a list of 12 SpatialPolygons
objects - make sure your object gives the same results as this, and test on a small sample before running on 30,000:
> length(spl)
[1] 12
> class(spl)
[1] "list"
> class(spl[[1]])
[1] "SpatialPolygons"
attr(,"package")
[1] "sp"
You want to create a single Spatial Polygons
object with all the features in it in order to then make a Spatial Polygons Data Frame:
> joined = SpatialPolygons(lapply(spl, function(x){x@polygons[[1]]}))
> plot(joined)
This takes the first polygons
slot from the object (and there should be only one, since each list element is currently a single feature) and then constructs a list of Polygons objects which is what you feed to SpatialPolygons
to make a multi-feature SpatialPolygons
. Plot this, and you should see all your features. Next, if you want to save as a shapefile
, you need to add some data. In the absence of anything else, I create a simple 1 to 12 ID column:
> jdata = SpatialPolygonsDataFrame(Sr=joined, data=data.frame(i=1:12),FALSE)
The FALSE
flag just stops R trying to rearrange the spatial and non-spatial data to match up. You might want to put the buffer sizes in the data frame or something.
Job done.
You can use the makeUniqueIDs argument in rbind if your polygons do not have unique IDs.
library(purrr)
list(buff.pts, makeUniqueIDs = T) %>%
flatten() %>%
do.call(rbind, .)