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
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:
Subscribe to:
Post Comments
(
Atom
)
Thanks to the anonymous commentator that pointed out that it is maptools package that needs to be loaded! (I accidentally deleted the comment.. sry)
ReplyDeletergdal::readOGR() works almost the same, but you need to strip the '.shp' from the end of the filenames:
ReplyDeleteshps <- 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.
Hi Tom,
DeleteYou'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
This line is formed incorrectly I think:
Deleteshps <- sub(shps,'\\.shp$')
It should be
shps <- sub(\\.shp$', "", shps)