# More Raster [ The R Script associated with this page is available here](06_RasterTwo.R). Download this file and open it (or copy-paste into a new script) with RStudio so you can follow along. ## Libraries ```r library(knitr) library(dplyr) library(tidyr) library(ggplot2) library(raster) library(rasterVis) library(scales) library(rgeos) ``` ## Today's question ### How will future (projected) sea level rise affect Bangladesh? 1. How much area is likely to be flooded by rising sea level? 2. How many people are likely to be displaced? 3. Will sea level rise affect any major population centers? ## Bangladesh ```r getData("ISO3")%>% as.data.frame%>% filter(NAME=="Bangladesh") ``` ``` ## ISO3 NAME ## 1 BGD Bangladesh ``` ### Download Bangladesh Border Often good idea to keep data in separate folder. You will need to edit this for your machine! ```r datadir="~/Downloads/data" if(!file.exists(datadir)) dir.create(datadir, recursive=T) ``` Download country border. ```r bgd=getData('GADM', country='BGD', level=0,path = datadir) plot(bgd) ```  ## Topography SRTM Elevation data with `getData()` as 5deg tiles. ```r bgdc=gCentroid(bgd)%>%coordinates() dem1=getData("SRTM",lat=bgdc[2],lon=bgdc[1],path=datadir) plot(dem1) plot(bgd,add=T) ```  ### Mosaicing/Merging rasters Download the remaining necessary tiles ```r dem2=getData("SRTM",lat=23.7,lon=85,path=datadir) ``` Use `merge()` to join two aligned rasters (origin, resolution, and projection). Or `mosaic()` combines with a function. ```r dem=merge(dem1,dem2) plot(dem) plot(bgd,add=T) ```  ## Saving/exporting rasters Beware of massive temporary files! ```r inMemory(dem) ``` ``` ## [1] FALSE ``` ```r dem@file@name ``` ``` ## [1] "/private/var/folders/lg/gz_jcfk5617dlpzdtg23x3rh0000gn/T/RtmpNAxz5l/raster/r_tmp_2016-10-23_204503_5034_04978.grd" ``` ```r file.size(sub("grd","gri",dem@file@name))*1e-6 ``` ``` ## [1] 144.036 ``` ```r showTmpFiles() ``` ``` ## r_tmp_2016-10-23_204503_5034_04978 ``` ```r rasterOptions() ``` ``` ## format : raster ## datatype : FLT8S ## overwrite : FALSE ## progress : none ## timer : FALSE ## chunksize : 1e+07 ## maxmemory : 1e+08 ## tmpdir : /var/folders/lg/gz_jcfk5617dlpzdtg23x3rh0000gn/T//RtmpNAxz5l/raster// ## tmptime : 168 ## setfileext : TRUE ## tolerance : 0.1 ## standardnames : TRUE ## warn depracat.: TRUE ## header : none ``` Set with `rasterOptions(tmpdir = "/tmp")` Saving raster to file: _two options_ Save while creating ```r dem=merge(dem1,dem2,filename=file.path(datadir,"dem.tif"),overwrite=T) ``` Or after ```r writeRaster(dem, filename = file.path(datadir,"dem.tif")) ``` ### WriteRaster formats Filetype Long name Default extension Multiband support --- --- --- --- raster 'Native' raster package format .grd Yes ascii ESRI Ascii .asc No SAGA SAGA GIS .sdat No IDRISI IDRISI .rst No CDF netCDF (requires `ncdf`) .nc Yes GTiff GeoTiff (requires rgdal) .tif Yes ENVI ENVI .hdr Labelled .envi Yes EHdr ESRI .hdr Labelled .bil Yes HFA Erdas Imagine Images (.img) .img Yes `rgdal` package does even more... ### Crop to Coastal area of Bangladesh ```r # Crop using border polygon # dem=crop(dem,bgd,filename=file.path(datadir,"dem_bgd.tif"),overwrite=T) # Or crop to a lat-lon box dem=crop(dem,extent(89,91.5,21.5,24),filename=file.path(datadir,"dem_bgd.tif"),overwrite=T) plot(dem); plot(bgd,add=T) ```  # Use ggplot ```r gplot(dem,max=1e5)+geom_tile(aes(fill=value))+ scale_fill_gradientn( colours=c("red","yellow","grey30","grey20","grey10"), trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e3)))+ coord_equal(ylim=c(21.5,24))+ geom_path(data=fortify(bgd), aes(x=long,y=lat,order=order,group=group),size=.5) ``` ``` ## Regions defined for each Polygons ```  # Terrain analysis (an aside) ## Terrain analysis options `terrain()` options: * slope * aspect * TPI (Topographic Position Index) * TRI (Terrain Ruggedness Index) * roughness * flowdir Use a smaller region: ```r reg1=crop(dem1,extent(93.8,94,21.05,21.15)) plot(reg1) ```  The terrain indices are according to Wilson et al. (2007), as in [gdaldem](http://www.gdal.org/gdaldem.html). ### Calculate slope ```r slope=terrain(reg1,opt="slope",unit="degrees") plot(slope) ```  ### Calculate aspect ```r aspect=terrain(reg1,opt="aspect",unit="degrees") plot(aspect) ```  ### TPI (Topographic Position Index) Difference between the value of a cell and the mean value of its 8 surrounding cells. ```r tpi=terrain(reg1,opt="TPI") gplot(tpi,max=1e6)+geom_tile(aes(fill=value))+ scale_fill_gradient2(low="blue",high="red",midpoint=0)+ coord_equal() ```  Negative values indicate valleys, near zero flat or mid-slope, and positive ridge and hill tops
* Population
* Pollution
* Energy
* Agriculture
* Roads
### Gridded Population of the World
Data _not_ available for direct download (e.g. `download.file()`)
* Log into SEDAC with an Earth Data Account
[http://sedac.ciesin.columbia.edu](http://sedac.ciesin.columbia.edu)
* Download Population Density Grid for 2015
### Load population data
Use `raster()` to load a raster from disk.
```r
pop_global=raster(file.path(datadir,"gpw-v4-population-density-2015/gpw-v4-population-density_2015.tif"))
plot(pop_global)
```

A nicer plot...
```r
gplot(pop_global,max=1e5)+geom_tile(aes(fill=value))+
scale_fill_gradientn(
colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e5)))+
coord_equal()
```

### Crop to region with the `dem` object
```r
pop=pop_global%>%
crop(dem)
gplot(pop,max=1e5)+geom_tile(aes(fill=value))+
scale_fill_gradientn(colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e5)))+
coord_equal()
```

### Resample to DEM
Compare the resolution and origin of `pop2` and `dem`.
```r
pop
```
```
## class : RasterLayer
## dimensions : 300, 300, 90000 (nrow, ncol, ncell)
## resolution : 0.008333333, 0.008333333 (x, y)
## extent : 89, 91.5, 21.5, 24 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## data source : in memory
## names : gpw.v4.population.density_2015
## values : 97.13571, 154258.4 (min, max)
```
```r
dem
```
```
## class : RasterLayer
## dimensions : 3000, 3000, 9e+06 (nrow, ncol, ncell)
## resolution : 0.0008333333, 0.0008333333 (x, y)
## extent : 88.99958, 91.49958, 21.49958, 23.99958 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## data source : /Users/adamw/Downloads/data/dem_bgd.tif
## names : dem_bgd
## values : -27, 152 (min, max)
```
```r
res(pop)
```
```
## [1] 0.008333333 0.008333333
```
```r
res(dem)
```
```
## [1] 0.0008333333 0.0008333333
```
```r
origin(pop)
```
```
## [1] 0 0
```
```r
origin(dem)
```
```
## [1] -0.000416061 -0.000416207
```
```r
# Look at average cell area in km^2
cellStats(raster::area(pop),"mean")
```
```
## [1] 0.7886268
```
```r
cellStats(raster::area(dem),"mean")
```
```
## [1] 0.007886292
```
So to work with these rasters (population and elevation), it is easiest to "adjust" them to have the same resolution. But there is no good way to do this. Do you aggregate the finer raster or resample the coarser one?
Assume equal density within each grid cell and resample
```r
pop_fine=pop%>%
resample(dem,method="bilinear")
gplot(pop_fine,max=1e5)+geom_tile(aes(fill=value))+
scale_fill_gradientn(
colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e5)))+
coord_equal()
```

50 different styles illustrated [here](https://cran.r-project.org/web/packages/plot3D/vignettes/volcano.pdf).
Overlay population with `drape`
```r
plot3D(dem,drape=pop3, zfac=1)
decorate3d()
```
## Raster overview
* Perform many GIS operations
* Convenient processing and workflows
* Some functions (e.g. `distance()` can be slow!