sp och S4

Visualisering av geospatial data i R

Charlotte Wickham

Assistant Professor at Oregon State University

Två typer av sp-objekt

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
Visualisering av geospatial data i R

SpatialPolygons-objekt

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
Visualisering av geospatial data i R

SpatialPolygonsDataFrame-objekt

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
Visualisering av geospatial data i R

S4

  • Ett av R:s objektorienterade (OO) system
  • Centrala OO-begrepp
    • Klass: definierar en objekttyp, dess attribut och relation till andra klasser
    • Metoder: funktioner vars beteende beror på indatans klass
  • S4-objekt kan ha en rekursiv struktur; elementen kallas slots
  • http://adv-r.had.co.nz/OO-essentials.html#s4
Visualisering av geospatial data i R

Åtkomst till slots

# 1. Använd en dedikerad metod
proj4string(countries_sp)
"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# 2. Använd @ följt av slotnamnet utan citattecken
countries_sp@proj4string
CRS arguments: +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
# 3. Använd slot() med slotnamnet inom citattecken
slot(countries_sp, "proj4string")
CRS arguments: +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
Visualisering av geospatial data i R

Nu kör vi en övning!

Visualisering av geospatial data i R

Preparing Video For Download...