1

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:
library(rgdal)
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?

1
  • 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. Oct 27, 2020 at 22:26

1 Answer 1

1

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

first=TRUE
for(shp in shapefiles){
   # this function reads in a shapefile from shp and returns sp object:
   shpdata = read_in_and_check(shp)
   if(first){
      output=shpdata
      first=FALSE
   } 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)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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