Spatial data in R, sp classes and projections

The slots of spatial data

load("../data/lnd.RData")
slotNames(lnd)
## [1] "data"        "polygons"    "plotOrder"   "bbox"        "proj4string"
lnd@bbox
##        min      max
## x 503571.2 561941.1
## y 155850.8 200932.5

Seeing the geometry

lnd@polygons[[1]]@Polygons[[1]]@coords[1:5,]
##          [,1]     [,2]
## [1,] 541177.7 173555.7
## [2,] 541872.2 173305.8
## [3,] 543441.5 171429.9
## [4,] 544361.6 172379.2
## [5,] 546662.4 170451.9
plot(lnd@polygons[[1]]@Polygons[[1]]@coords)

Seeing the data

head(lnd@data[1:2,1:3])
##   ons_label                 name Partic_Per
## 1      00AF              Bromley       21.7
## 2      00BD Richmond upon Thames       26.6

Subsetting spatial objects

lnd5 = lnd[5,]
plot(lnd5)

What just happened?

A new object was created, a subset of lnd, with the same class.

class(lnd)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
class(lnd5)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
nrow(lnd)
## [1] 33
nrow(lnd5)
## [1] 1

Subsetting based on attributes

We can select spatial objects based on their attributes. Sometimes it can help to first create a selection object:

sel = lnd$Pop_2001 > median(lnd$Pop_2001)
lnd_highpop = lnd[sel,]
plot(lnd_highpop)

Adding together different selections

plot(lnd)
plot(lnd_highpop, add = TRUE, col = "red")

Note: it would be better to do this with tmap.

Illustration with tmap

library(tmap)
lnd$colour = "white"
lnd$colour[sel] = "black"
qtm(lnd, fill = "colour")

Loading, plotting and interrogating spatial data

Pages 8 - 10

Transformations

lnd = raster::shapefile("../data/lnd-stns.shp")
proj4string(lnd)
## [1] "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
bbox(lnd)
##                 min        max
## coords.x1 -1.199066  0.9358515
## coords.x2 50.984598 51.9398978
lnd_osgb = spTransform(lnd, CRSobj = "+init=epsg:27700")
bbox(lnd_osgb)
##              min    max
## coords.x1 455435 602523
## coords.x2 122266 227704

Manipulating spatial objects

Pages 11 - 17