I have several polygon shapefiles that I need to merge into one using a loop in R. I want to start with an empty shapefile and merge it with the existing shapefiles. All shapefiles will be chacked before the merge that they have the same fields.

I can think of two options:

  1. create an empty shapefile in ArcMap and read it into R. I tried this with readOGR and got an error:
EI_GIS_ALL = readOGR(dsn = EI_GIS_ALL_dsn, layer=EI_GIS_ALL_FileName)
Error in readOGR(dsn = EI_GIS_ALL_dsn, layer = EI_GIS_ALL_FileName) : 
  no features found
  1. Create an empty shapefile in R and use union to merge it with existing shapefiles. The union is like in maycca's solution in Merging multiple SpatialPolygonDataFrames into 1 SPDF in R?

Any suggestions?

  • Spacedman nailed it but, I would add that you can avoid unique row.name issues by using sf and then coercing to sp. First create names vector shp <- list.files(getwd(), "shp$") then read in data s <- lapply(shp, function(x) sf::st_read(x) ) finally, merge and coerce to sp s <- as(do.call(rbind, s), "Spatial") With large data you will also get better read times. – Jeffrey Evans Oct 27 '20 at 22:26

Probably easier to use another pattern, eg special treatment of the first item:

for(shp in shapefiles){
   # this function reads in a shapefile from shp and returns sp object:
   shpdata = read_in_and_check(shp)
   } else {
      output=bind(output, shpdata)

or get your shapes into a list and use do.call with bind:

# shpdatas becomes a list of sp-class objects:
shpdatas = lapply(shapefiles, read_in_and_check)
output = do.call(bind, shpdatas)
  • Perfect! Thanks – Ilik Oct 27 '20 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.