Things I Forget: Reading a Shapefile in R with readOGR

[This article was first published on Landscape Ecology 2.0 » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: Landscape Ecology 2.0 » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)