10 Sept 2013

Loading Multiple Shapefiles to the R-Console Simultaneously

A quick tip on how to load multiple shapefiles (point shapefiles, i.e.) to the R console in one go:

library(maptools)

# get all files with the .shp extension from working directory 
setwd("D:/GIS_DataBase/GIS_Tirol/Tirol_Verbreitungskarten/Verbreitungs_Daten")

shps <- dir(getwd(), "*.shp")

# the assign function will take the string representing shp and turn it into a variable
# which holds the spatial points data
for (shp in shps) assign(shp, readShapePoints(shp))
plot(get(shp[1])) # i.e.
# ...done

4 comments :

  1. Thanks to the anonymous commentator that pointed out that it is maptools package that needs to be loaded! (I accidentally deleted the comment.. sry)

    ReplyDelete
  2. rgdal::readOGR() works almost the same, but you need to strip the '.shp' from the end of the filenames:
    shps <- dir(getwd(), "*.shp")
    shps <- sub(shps,'\\.shp$')
    for (shp in shps) assign(shp, readOGR('.',layer=shp))

    You could, of course, replace the for (shp in shps) loop with lapply(), but this is one of the cases where a loop is as fast as a *apply() function.

    ReplyDelete
    Replies
    1. Hi Tom,
      You're right readOGR actually is a better choice because it reads the projection, if there is one assigned to the shapefile (.prj-file). I'm no orthodox lapply follower, and, as you said, it is not faster or better than
      the for-loop here.
      Regards, Kay

      Delete
    2. This line is formed incorrectly I think:

      shps <- sub(shps,'\\.shp$')

      It should be

      shps <- sub(\\.shp$', "", shps)

      Delete