Dave_L
Dave_L

Reputation: 383

Combine blocks of sp spatial data into a single block

I have 8 shape files each containing the outlines of many river catchments. I've used a combination of rgdal, rgeos and sp to read these and form a list of 8 SpatialPolygonsDataFrame objects. The code I used is as follows:

unit.num <- c(13,18,19,29,41,75,79,80)
GetCatchmentShapes <- function(x) {
  file.name <- paste("GFMUnit",x,"_GFES_Watersheds_WGS84.shp",sep="")
  con = file.path(project.folder,"RawData","Watersheds","GFES Watersheds",file.name)
  catchment.list <- readOGR(con,ogrListLayers(con)) 
}
all.catchments <- sapply(unit.num, GetCatchmentShapes)

How can I combine the 8 elements of all.catchments into a single SpatialPolygonsDataFrame object?

Upvotes: 1

Views: 125

Answers (2)

jlhoward
jlhoward

Reputation: 59365

You can use the spChFIDs(...) function in package sp to change the polygon IDs to unique values, then use rbind(...) to combine the spatialPolygonDataFrame objects.

Here is an example using the shapefiles for France, Italy, and Germany.

## example dataset; shapfiles for France, Italy, Germany
## you have this already...
library(raster)
FR <- getData("GADM",country="FRA",level=1)
IT <- getData("GADM",country="ITA",level=1)
GR <- getData("GADM",country="DEU",level=1)
spList <- list(FR,IT,GR)    # list of country shapefiles

# you start here...
library(sp)   # loaded with `rgdal`
set.IDS <- function(sp,i) spChFIDs(sp,paste(i,rownames(sp@data),sep="."))
result  <- do.call(rbind,mapply(set.IDS,spList,seq_along(spList)))
plot(result)

Upvotes: 3

jbaums
jbaums

Reputation: 27388

This is a bit messy, and there's likely a better way to create unique row IDs, but here goes anyway:

Assuming your list of SpatialPolygonsDataFrames is called spdf_list, and that all elements have the same set of fields:

spdf_list <- 
  mapply(spChFIDs, spdf_list, 
         split(as.character(seq_len(sum(sapply(spdf_list, length)))), 
               unlist(mapply(rep, seq_along(spdf_list), 
                             each=sapply(spdf_list, length)))))

single <- do.call(rbind, spdf_list)

Upvotes: 1

Related Questions