Quantcast
Channel: r software hub
Viewing all articles
Browse latest Browse all 1015

R and GIS – working with shapefiles

$
0
0

By R – StudyTrails

Selection_172

R has some very useful libraries for working with spatial data. In this blog we will look at some of the libraries and demonstrate few basic functionalities. Lets start with reading a shapefile.

How to read a shapefile :

We will use the maptools package to read the shape file. Along with the maptools package, install the rgeos and sp packages. They will come handy later on.
To demonstrate reading a shapefile, we use the shapefile of US states which we download from here. The zip folder contains the file statesp020.shp which we will attempt to read. Lets first specify the projection that we want to use to read data in. The shapefile contains polygons in WGS84 projection, so lets define an object to hold that projection.

> library(maptools)
Loading required package: sp
Checking rgeos availability: TRUE

> crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")

The CRS class is present in the sp package and it holds the projection definition in proj4j format. We now read the shapefile

> states=readShapePoly("/home/mithil/java/R/statesp020.shp",proj4string=crswgs84,verbose=TRUE)

The shapefile is now read and stored into an object called “states”. readShapePoly function is used to read a shapefile that contains polygons. Lets explore the object that is created, beginning with what type it is.

> class(states)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

So the object is of type SpatialPolygonsDataFrame. This comes from the sp package. This object has 5 slots – data, polygons, bbox, plotOrder,bbox, proj4string. data contains the information about the polygons, polygons contains the actual polygon coordinates, bbox is the bounding box drawn around the boundaries of the shapefile and the proj4string is the projection.

> str([email protected])
'data.frame': 2895 obs. of 9 variables:
$ AREA : num 267 0 0 0 0 ...
$ PERIMETER : num 374.768 0.224 0.118 0.276 0.167 ...
$ STATESP020: int 2 3 4 5 6 7 8 9 10 11 ...
...read more

Source:: r-bloggers.com


Viewing all articles
Browse latest Browse all 1015