Things I Forget: Reading a Shapefile in R with readOGR

September 27, 2013
By

(This article was first published on Landscape Ecology 2.0 » R, and kindly contributed to R-bloggers)

One of the more common ways that I read vector data into R is via shapefiles.  I tend to use these partly becuase of my own sordid past with Arc/INFO, ArcView and ArcGIS and partly due to their ubiquity.  In any event I have found the R package, rgdal, indespensible for this.  One of the workhorse functions for pulling in vector data is readOGR().  It has two required parameters dsn and  layer. The part I never remember is how these relate to shapefiles. There is nothing especially tricky about it, I just tend to forget what the dsn is and what the layer is. In short the dsn is the directory (without a trailing backslash) and the layer is the shapefile name without the .shp.

So, here’s the actual code so I don’t have to look it up again.

If the shapefile you are reading is in your current working directory the dsn refers simply to that directory. So all you need is simply a “.”. The layer is the name of shapefile without an extension. So it would look something like:

myShapeInR<-readOGR(".","myShapeFile")


Now, if that file resides elsewhere, the trick is to remember what the heck dsn refers to. Again it is simply the directory where the shapefile resides. So if I had a shapefile in a place like C:/data I would use the command like:

myShapeInR<-readOGR("C:/data","myShapeFile")


There, it is really quite simple, yet I always mess it up. Not any more.

I hope.

Filed under: Programming, R, Things I Forget Tagged: GIS, Landscape Ecology, R, readOGR, rgdal, shapefiles

To leave a comment for the author, please follow the link and comment on his blog: Landscape Ecology 2.0 » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.