[Open presentation in a new tab](presentations/PS_06_raster.html){target="_blank"}
_Click on presentation and then use the space bar to advance to the next slide or escape key to show an overview._
## Download
| [ R Script](scripts/05_Raster_nocomments.R) | [ Commented R Script](scripts/05_Raster.R) | [ Rmd Script](scripts/05_Raster.Rmd)|
|:--:|:-:|:-:|
## Libraries
```r
library(dplyr)
library(tidyr)
library(sp)
library(ggplot2)
library(rgeos)
library(maptools)
# load data for this course
# devtools::install_github("adammwilson/DataScienceData")
library(DataScienceData)
# New libraries
library(raster)
library(rasterVis) #visualization library for raster
```
# Raster Package
## `getData()`
Raster package includes access to some useful (vector and raster) datasets with `getData()`:
* Elevation (SRTM 90m resolution raster)
* World Climate (Tmin, Tmax, Precip, BioClim rasters)
* Countries from CIA factsheet (vector!)
* Global Administrative boundaries (vector!)
`getData()` steps for GADM:
1. _Select Dataset_: ‘GADM’ returns the global administrative boundaries.
2. _Select country_: Country name of the boundaries using its ISO A3 country code
3. _Specify level_: Level of of administrative subdivision (0=country, 1=first level subdivision).
## GADM: Global Administrative Areas
Administrative areas in this database are countries and lower level subdivisions.
Divided by country (see website for full dataset). Explore country list:
```r
getData("ISO3")%>%
as.data.frame%>%
filter(NAME=="South Africa")
```
```
## ISO3 NAME
## 1 ZAF South Africa
```
Download data for South Africa
```r
za=getData('GADM', country='ZAF', level=1)
```
Or use the version in the DataScienceData
```r
data(southAfrica)
za=southAfrica # rename for convenience
```
```r
plot(za)
```
Danger: `plot()` works, but can be slow for complex polygons. If you want to speed it up, you can plot a simplified version as follows:
```r
za %>% gSimplify(0.01) %>% plot()
```

### Check out attribute table
```r
za@data
```
```
## OBJECTID ID_0 ISO NAME_0 ID_1 NAME_1 HASC_1 CCN_1 CCA_1
## 1 1 211 ZAF South Africa 1 Eastern Cape ZA.EC NA EC
## 2 2 211 ZAF South Africa 2 Free State ZA.FS NA FS
## 3 3 211 ZAF South Africa 3 Gauteng ZA.GT NA GT
## 4 4 211 ZAF South Africa 4 KwaZulu-Natal ZA.NL NA KZN
## 5 5 211 ZAF South Africa 5 Limpopo ZA.NP NA LIM
## 6 6 211 ZAF South Africa 6 Mpumalanga ZA.MP NA MP
## 7 7 211 ZAF South Africa 7 North West ZA.NW NA NW
## 8 8 211 ZAF South Africa 8 Northern Cape ZA.NC NA NC
## 9 9 211 ZAF South Africa 9 Western Cape ZA.WC NA WC
## TYPE_1 ENGTYPE_1 NL_NAME_1
## 1 Provinsie Province
## 2 Provinsie Province
## 3 Provinsie Province
## 4 Provinsie Province
## 5 Provinsie Province
## 6 Provinsie Province
## 7 Provinsie Province
## 8 Provinsie Province
## 9 Provinsie Province
## VARNAME_1
## 1 Oos-Kaap
## 2 Orange Free State|Vrystaat
## 3 Pretoria/Witwatersrand/Vaal
## 4 Natal and Zululand
## 5 Noordelike Provinsie|Northern Transvaal|Northern Province
## 6 Eastern Transvaal
## 7 North-West|Noordwes
## 8 Noord-Kaap
## 9 Wes-Kaap
```
Plot a subsetted region:
```r
subset(za,NAME_1=="Western Cape") %>% gSimplify(0.01) %>%
plot()
```

## Your turn
Use the method above to download and plot the boundaries for a country of your choice.
Raster memory usage
```r
inMemory(r)
```
```
## [1] TRUE
```
> You can change the memory options using the `maxmemory` option in `rasterOptions()`
## Raster Plotting
Plotting is easy (but slow) with `plot`.
```r
plot(r, main='Raster with 100 cells')
```

### ggplot and rasterVis
rasterVis package has `gplot()` for plotting raster data in the `ggplot()` framework.
```r
gplot(r,maxpixels=50000)+
geom_raster(aes(fill=value))
```

Adjust `maxpixels` for faster plotting of large datasets.
```r
gplot(r,maxpixels=10)+
geom_raster(aes(fill=value))
```

Can use all the `ggplot` color ramps, etc.
```r
gplot(r)+geom_raster(aes(fill=value))+
scale_fill_distiller(palette="OrRd")
```

## Spatial Projections
Raster package uses standard [coordinate reference system (CRS)](http://www.spatialreference.org).
For example, see the projection format for the [_standard_ WGS84](http://www.spatialreference.org/ref/epsg/4326/).
```r
projection(r)
```
```
## [1] "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
```
## Warping rasters
Use `projectRaster()` to _warp_ to a different projection.
`method=` `ngb` (for categorical) or `bilinear` (continuous)
```r
r2=projectRaster(r,crs="+proj=sinu +lon_0=0",method = "ngb")
```
```
## Warning in rgdal::rawTransform(projto_int, projfrom, nrow(xy), xy[, 1], :
## 48 projected point(s) not finite
```
```r
par(mfrow=c(1,2));plot(r);plot(r2)
```

# WorldClim
## Overview of WorldClim
Mean monthly climate and derived variables interpolated from weather stations on a 30 arc-second (~1km) grid.
See [worldclim.org](http://www.worldclim.org/methods)
## Bioclim variables
Variable Description
- -
BIO1 Annual Mean Temperature
BIO2 Mean Diurnal Range (Mean of monthly (max temp – min temp))
BIO3 Isothermality (BIO2/BIO7) (* 100)
BIO4 Temperature Seasonality (standard deviation *100)
BIO5 Max Temperature of Warmest Month
BIO6 Min Temperature of Coldest Month
BIO7 Temperature Annual Range (BIO5-BIO6)
BIO8 Mean Temperature of Wettest Quarter
BIO9 Mean Temperature of Driest Quarter
BIO10 Mean Temperature of Warmest Quarter
BIO11 Mean Temperature of Coldest Quarter
BIO12 Annual Precipitation
BIO13 Precipitation of Wettest Month
BIO14 Precipitation of Driest Month
BIO15 Precipitation Seasonality (Coefficient of Variation)
BIO16 Precipitation of Wettest Quarter
BIO17 Precipitation of Driest Quarter
BIO18 Precipitation of Warmest Quarter
BIO19 Precipitation of Coldest Quarter
## Download climate data
Download the data:
```r
clim=raster::getData('worldclim', var='bio', res=10)
```
`res` is resolution (0.5, 2.5, 5, and 10 minutes of a degree)
Instead of downloading the full dataset, we'll use the copy in the `DataScienceData` package:
```r
data(worldclim)
#rename for convenience
clim=worldclim
```
### Gain and Offset
```r
clim
```
```
## class : RasterStack
## dimensions : 900, 2160, 1944000, 19 (nrow, ncol, ncell, nlayers)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : -180, 180, -60, 90 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
## names : bio1, bio2, bio3, bio4, bio5, bio6, bio7, bio8, bio9, bio10, bio11, bio12, bio13, bio14, bio15, ...
## min values : -269, 9, 8, 72, -59, -547, 53, -251, -450, -97, -488, 0, 0, 0, 0, ...
## max values : 314, 211, 95, 22673, 489, 258, 725, 375, 364, 380, 289, 9916, 2088, 652, 261, ...
```
Note the min/max of the raster. What are the units? Always check metadata, the [WorldClim temperature dataset](http://www.worldclim.org/formats) has a `gain` of 0.1, meaning that it must be multipled by 0.1 to convert back to degrees Celsius. We'll set the temperature variables (see table above) to 0.1 and leave the others at 1.
```r
gain(clim)=c(rep(0.1,11),rep(1,7))
```
### Plot with `plot()`
```r
plot(clim)
```

## Faceting in ggplot
Or use `rasterVis` methods with gplot
```r
gplot(clim[[13:19]])+geom_raster(aes(fill=value))+
facet_wrap(~variable)+
scale_fill_gradientn(colours=c("brown","red","yellow","darkgreen","green"),trans="log10")+
coord_equal()
```
```
## Warning: Transformation introduced infinite values in discrete y-axis
```

Let's dig a little deeper into the data object:
```r
## is it held in RAM?
inMemory(clim)
```
```
## [1] TRUE
```
```r
## How big is it?
object.size(clim)
```
```
## 295722384 bytes
```
```r
## can we work with it directly in RAM?
canProcessInMemory(clim)
```
```
## [1] TRUE
```
## Subsetting and spatial cropping
Use `[[1:3]]` to select raster layers from raster stack.
```r
## crop to a latitude/longitude box
r1 <- raster::crop(clim[[1]], extent(10,35,-35,-20))
## Crop using a Spatial polygon
r1 <- raster::crop(clim[[1]], bbox(za))
```
```r
r1
```
```
## class : RasterLayer
## dimensions : 76, 98, 7448 (nrow, ncol, ncell)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : 16.5, 32.83333, -34.83333, -22.16667 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
## data source : in memory
## names : bio1
## values : 5.8, 24.6 (min, max)
```
```r
plot(r1)
```

## Spatial aggregation
```r
## aggregate using a function
aggregate(r1, 3, fun=mean) %>%
plot()
```

## Your turn
Create a new raster by aggregating to the minimum (`min`) value of `r1` within a 10 pixel window
## Focal ("moving window")
```r
## apply a function over a moving window
focal(r1, w=matrix(1,3,3), fun=mean) %>%
plot()
```

```r
## apply a function over a moving window
rf_min <- focal(r1, w=matrix(1,11,11), fun=min)
rf_max <- focal(r1, w=matrix(1,11,11), fun=max)
rf_range=rf_max-rf_min
## or do it all at once
range2=function(x,na.rm=F) {
max(x,na.rm)-min(x,na.rm)
}
rf_range2 <- focal(r1, w=matrix(1,11,11), fun=range2)
plot(rf_range)
```

```r
plot(rf_range2)
```

## Your turn
Plot the focal standard deviation of `r1` over a 3x3 window.