I have a directory that contains around 700 .shp files. I want to create a map in R that displays all of them. The easiest way i could think to do this was to bind them all together and then use ggplot2 to create a map. here is my code to read the files and create a list containing the files:

dir <- "./Basins/separate_basins/"
basins <- list.files(dir, pattern = "\\.shp$")
basins <- unique(file_path_sans_ext(basins))
cord <- "+init=epsg:2163"
templist <- list()

for (i in basins){ 

  thisbasin <- readOGR(dsn=dir, layer=i)
  thisbasin <- spTransform(thisbasin, cord)
  templist[[i]] <- data.frame(thisbasin)

I then try to use the bind function to bind all of the components in the list together: test_bind <- bind(templist) Then I tried to test if this works using `plot(test_bind) but it prints like this: enter image description here

I want to display the polygons that are present in the original .shp files. how can I fix this?


Your code is coercing the data into a data.frame before piping into the list object so, don't do that. I would recommend some small changes to your code and then using do.call on the list to bind the results into a single sp SpatialPolygonsDataFrame object.

templist <- list() 
  for (i in 1:length(basins)){ 
    thisbasin <- readOGR(dsn=dir, layer=basins[i])
    templist[[i]] <- spTransform(thisbasin, cord)
basins <- do.call("rbind", templist)

At this point, since you want to plot using ggplot2, I would recommend coercing to an sf object.

  • 1
    BTW if you go to sf best to start with sf x <- do.call(rbind, lapply(list.files(dir, pattern = "shp$", full.names = TRUE), sf::read_sf)) - will be faster, no need for dropping .shp etc. – mdsumner Nov 28 '18 at 6:19

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.