Today

  • terra continued
    • making rasters, conversions, etc
    • calculations
    • zonal
    • focal
    • global
    • terrain

Data

library(geospaar)
farmers <- system.file("extdata/farmer_spatial.csv", package = "geospaar") %>% 
  read_csv() %>% 
  st_as_sf(coords = c("x", "y"))
districts <- st_read(
  system.file("extdata/districts.geojson", package = "geospaar")
)
roads <- read_sf(system.file("extdata/roads.geojson", package = "geospaar"))

chirps <- terra::rast(system.file("extdata/chirps.tif", package = "geospaar"))

b <- lapply(1:10, function(x) {
  r <- rast(ext(30, 31, -14, -13), resolution = 0.1, 
            crs = "EPSG:4326")
  set.seed(x)
  values(r) <- sample(1:10, size = ncell(r), replace = TRUE)
  r
}) %>% do.call(c, .)
names(b) <- paste0("b", 1:10)

plot(b)

Plotting

  • run examples below individually
plot(b)
plot(b2)
plot_noaxes(b)
plot_noaxes(b2, main = paste("Random", 1:10))
plot(b2, main = paste("Random", 1:10))
plot_noaxes(b, legend = FALSE)
plot_noaxes(b[[1]], legend = FALSE)
legend("right", legend = 1:10, fill = terrain.colors(10), border = FALSE, 
       bty = "n")
# plotting with larger datasets
plot_noaxes(b, main = paste("Random", 1:10))
plot_noaxes(b, nc = 3, nr = 4, main = paste("Random", 1:10))
  • rasterVis package includes additional plot options
rasterVis::levelplot(b)#, #names.attr = paste("Random", 1:10))
rasterVis::levelplot(b, names.attr = paste("Random", 1:10))
rasterVis::levelplot(b[[1]])
rasterVis::gplot(b[[1]]) + geom_tile(aes(fill = value)) + 
  scale_fill_viridis_c()
  • ggplot() works with geom_raster()
ggplot2::ggplot(as.data.frame(b[[1]], xy = TRUE)) + 
  # geom_tile(aes(x = x, y = y, fill = dummy)) + scale_fill_viridis_c()  
  geom_raster(aes(x = x, y = y, fill = dummy)) + scale_fill_viridis_c()
  • stars package
stars::st_as_stars(b) %>% 
  plot(col = viridis::viridis(10))
stars::st_as_stars(b) %>% 
  plot()

Raster to other types

plot(b)
b[1:10]
b[1:ncell(b)]
as.matrix(b)
as.data.frame(b) %>% as_tibble()

Pre-processing

  • Aggregating/disaggregating
  • what is default method for aggregating?
plot(b, main = paste0("B", 1:2) )
aggregate(b, fact = 2) %>% 
  plot(., main = paste0("B agg", 1:2) )
# aggregate(b, fun = min, fact = 2) %>% plot
# aggregate(b, fun = sd, fact = 2) %>% plot

Pre-processing

  • what is default method for disaggregating?
plot(b, main = paste0("B ", 1:2) )
disagg(b, fact = 2) %>% 
  plot(., main = paste0("B disagg", 1:2) )
disagg(b, fact = 2, method = 'bilinear') %>% 
  plot(., main = paste0("B disagg bilinear", 1:2) )
  • Masking
  • mask makes values NA outside of mask area.
plot_noaxes(chirps[[1]])
chirpsz <- mask(chirps, districts)
plot_noaxes(chirpsz[[1]])
plot(st_geometry(districts), add = TRUE)
# rasterVis::levelplot(chirpsz[[1:5]])

Calculations

  • raster algebra
  • statistics
  • z dimension stats

Calculations

  • math operations work cell-wise
rf1 <- chirpsz[[1]] + chirpsz[[2]]
rf2 <- chirpsz[[1]] * 5
# dev.off()
plot(rf1 / 1000)
plot(((log10(rf1 + 1) * 10) / 5)^2)

Terrain analysis with zonal statistics

districts <- st_read(
  system.file("extdata/districts.geojson", package = "geospaar")
) 
districts <- districts %>% 
  mutate(ID = 1:nrow(.))
distsr <- rasterize(x = districts, y = raintot, field = "ID") 

# Download DEM
# dem <- getData(name = "alt", country = "ZMB", path = tempdir())
dem <- geodata::elevation_30s(country = "Zambia",  path = tempdir())

# calculate slope
slope <- terrain(x = dem, v = 'slope', unit = 'degrees')
plot(slope)

# calculate mean by district
distsr_rs <- resample(x = distsr, y = slope, method = "near")
plot(distsr_rs)
zoneslope <- zonal(x = slope, z = distsr_rs, fun = "mean", na.rm = TRUE)
hist(zoneslope[, 2])
zoneelevation <- zonal(x = dem, z = distsr_rs, fun = "mean", na.rm = TRUE)
hist(zoneelevation[, 2])

Subst

# map zonal statistics
distr_slopes <- subst(x = distsr_rs, from = zoneslope$ID, 
                      to = zoneslope$slope)
distr_elevzone <- subst(x = distsr_rs, from = zoneelevation$ID, 
                        to = zoneelevation$ZMB_elv_msk)

# plot
plot(s[[2]])
s <- c(distr_elevzone, distr_slopes)
titles <- c("Elevation", "Slope")
par(mfrow = c(1, 2))
for(i in 1:length(s)) {
  plot_noaxes(s[[i]], main = titles[i])
}

Climate data summaries and zonal stats

dt <- as.Date(gsub("Y", "", names(chirpsz)), format = "%y%j")
dt <- lubridate::parse_date_time(gsub("Y", "", names(chirpsz)), orders = "yj")
wk <- lubridate::week(dt)
weekly_rainfall <- lapply(unique(wk), function(x) {
  app(chirpsz[[which(wk == x)]], sum)
}) %>% do.call(c, .)
names(weekly_rainfall) <- paste0("wk", unique(wk))

rflim <- range(global(weekly_rainfall, range, na.rm = TRUE))
plot(weekly_rainfall, zlim = rflim)

Distance

  • plot distance from points
  • points must be in same projection as model raster
set.seed(1)
randsamp <- spatSample(rast(raintotalb), size = 10, xy = TRUE) %>%
  as_tibble %>%
  st_as_sf(coords = c("x", "y")) %>% 
  drop_na()
st_crs(randsamp) <- crs(raintotalb)
# #2
ptdistr <- terra::distance(rast(raintotalb), vect(randsamp))
ptdistrmsk <- mask(ptdistr, rast(raintotalb))
plot(ptdistrmsk)