reading shape files in R

[This article was first published on geo-affine » 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.

If I would like to adjust a shape file I normally used the way over an excel file or a text file to get a table and to join this with an existing shape file. Due to the sp and rgdal packages in R you can manipulate shapefiles directly in R:


now lets map the world boarders. You can find a little dataset for that here:
Now lets load the shape file (after decompressing the archive):

ogrListLayers("TM_WORLD_BORDERS_SIMPL-0.3.shp") #will show you available layers for the above dataset
shape=readOGR("TM_WORLD_BORDERS_SIMPL-0.3.shp", layer="TM_WORLD_BORDERS_SIMPL-0.3") #will load the shapefile to your dataset.
plot(shape) #to get an overview

and of course you can work with the data:


You are also able to create a new attribute and use the “match” function to create new data in distinct objects like countries.

shape$members = 1:nrow(shape) #adds the attribute members
shape$members[match(c("Austria","Germany","China","United Kingdom", "Switzerland", "Canada", "Ireland", "India","Poland","South Africa", "France","New Zealand", "Italy"), shape$NAME)]=c(3,6,1,2,24,1,2,2,1,1,2,1,2) #will make new values at given countries
plot(shape, col=gray(1-shape$members/max(shape$members))) #adjust the colorramp
writeOGR(shape, "/home/rikl/wd_r/", "Rmetric_participants", driver="ESRI Shapefile") #save it on your drive.

ENJOY your shape file!

participants at RMetrics 2012 (click to enlarge)

To leave a comment for the author, please follow the link and comment on their blog: geo-affine » R. 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)