sp and S4

Visualizing Geospatial Data in R

Charlotte Wickham

Assistant Professor at Oregon State University

Two types of sp object

summary(countries_sp)
Object of class SpatialPolygons
Coordinates:
   min       max
x -180 180.00000
y  -90  83.64513
Is projected: FALSE 
proj4string :
[+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 
  +towgs84=0,0,0]
summary(countries_spdf)
Object of class SpatialPolygonsDataFrame
Coordinates:
   min       max
x -180 180.00000
y  -90  83.64513
Is projected: FALSE 
proj4string :
[+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 
  +towgs84=0,0,0]
Data attributes:
     name              iso_a3          
 Length:177         Length:177         
 Class :character   Class :character   
 Mode  :character   Mode  :character
Visualizing Geospatial Data in R

SpatialPolygons object

str(countries_sp, max.level = 2)
Formal class 'SpatialPolygons' [package "sp"] with 4 slots
  ..@ polygons   :List of 177
  .. .. [list output truncated]
  ..@ plotOrder  : int [1:177] 7 136 28 169 31 23 9 66 84 5 ...
  ..@ bbox       : num [1:2, 1:2] -180 -90 180 83.6
  .. ..- attr(*, "dimnames")=List of 2
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
Visualizing Geospatial Data in R

SpatialPolygonsDataframe object

str(countries_spdf, max.level = 2)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
  ..@ data       :'data.frame':    177 obs. of  6 variables:
  ..@ polygons   :List of 177
  .. .. [list output truncated]
  ..@ plotOrder  : int [1:177] 7 136 28 169 31 23 9 66 84 5 ...
  ..@ bbox       : num [1:2, 1:2] -180 -90 180 83.6
  .. ..- attr(*, "dimnames")=List of 2
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
Visualizing Geospatial Data in R

S4

  • One of R's object-oriented (OO) systems
  • Key OO concepts
    • Class: defines a type of object, their attributes and their relationship to other classes
    • Methods: functions, behavior depends on class of input
  • S4 objects can have a recursive structure, elements are called slots
  • http://adv-r.had.co.nz/OO-essentials.html#s4
Visualizing Geospatial Data in R

Accessing slots

# 1. Use a dedicated method
proj4string(countries_sp)
"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# 2. Use the @ followed by unquoted slot name
countries_sp@proj4string
CRS arguments: +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
# 3. Use slot() with quoted slot name
slot(countries_sp, "proj4string")
CRS arguments: +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
Visualizing Geospatial Data in R

Let's practice!

Visualizing Geospatial Data in R

Preparing Video For Download...