The raster package

Visualizing Geospatial Data in R

Charlotte Wickham

Assistant Professor at Oregon State University

Data frames aren't great for storing spatial data

head(preds)
        lon      lat predicted_price
1 -123.3168 44.52539        258936.2
2 -123.3168 44.52740        257258.4
3 -123.3168 44.52940        255543.1
4 -123.3168 44.53141        253791.0
5 -123.3168 44.53342        252002.4
6 -123.3168 44.53542        250178.7
  • No CRS information
  • Inefficient storage
  • Inefficient display
Visualizing Geospatial Data in R

A better structure for raster data

  • Data matrix + information on grid + CRS

raster_structure.png

Visualizing Geospatial Data in R

The raster package

  • sp provides some raster data classes:
    • SpatialGrid, SpatialPixels, SpatialGridDataFrame, SpatialPixelsDataFrame
  • But raster is better:
    • Easier import of rasters
    • Large rasters aren't read into memory
    • Provides functions for raster type operations
  • Also uses S4 and when appropriate provides same functions
Visualizing Geospatial Data in R

raster provides print methods for sp objects

library(sp)
countries_spdf
An object of class "SpatialPolygonsDataFrame"
Slot "data":
                      name iso_a3 population         gdp                  region
1              Afghanistan    AFG   28400000    22270.00  
2                   Angola    AGO   12799293   110300.00  
3                  Albania    ALB    3639453    21810.00  
...
Slot "proj4string":
CRS arguments:
 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
Visualizing Geospatial Data in R

raster provides print methods for sp objects

library(raster)
countries_spdf
class       : SpatialPolygonsDataFrame 
features    : 177 
extent      : -180, 180, -90, 83.64513  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 ...
variables   : 6
names       :        name, iso_a3, population,         gdp, 
min values  : Afghanistan,    -99,        140,       16.00, 
max values  :    Zimbabwe,    ZWE, 1338612970, 15094000.00, ...
Visualizing Geospatial Data in R

Let's practice!

Visualizing Geospatial Data in R

Preparing Video For Download...