library(leaflet)
library(sf)
library(dplyr)
districts <- read_sf(
  system.file("extdata/districts.geojson", package = "geospaar")
)
bb <- unname(st_bbox(districts))
xy <- st_centroid(districts) %>% st_coordinates() %>% 
  bind_cols(name = districts$distName, .)
slist <- list("color" = "white")
label_opts <- labelOptions(noHide = TRUE, style = slist, direction = 'center',
                           textOnly = TRUE, textsize = "5px")

m <- leaflet() %>% 
  addProviderTiles("Esri.WorldImagery") %>% 
  fitBounds(bb[1], bb[2], bb[3], bb[4]) %>% 
  addPolygons(data = districts, fill = FALSE, color = "white", 
              group = "Districts", weight = 1) %>% 
  addLabelOnlyMarkers(xy$X, xy$Y, label = xy$name, group = "Names",
                      labelOptions = label_opts) %>%
  addLayersControl(overlayGroups = c("Districts", "Names"),
                   options = layersControlOptions(collapsed = FALSE,
                                                  autoZIndex = FALSE))

Today

  • Assignments
  • Bring Your Own Data
  • Continue on manipulating, plotting, analyzing data

BYOD

??

Reading, reshaping, analyzing, plotting

dat <- readr::read_csv(
  system.file("extdata/FAOSTAT_maize.csv", package = "geospaar")
)

Selecting, renaming, reshaping, mutating

  • Question: how can we describe the shape of this dataset?
  • Follow along:
    • select columns of interest
    • rename to make more tractable
    • reshape: pivot values into different columns, and some light renaming
    • mutate: make a yield column

Joining

  • Follow along
    • separate datasets by quantity (ha, prod, yield)
    • join by country, crop, year
      • test different kinds of joins (drop some rows to see effects)
      • arrange joins by country, year, etc

SAC

  • Base
sapply(sort(unique(dat_wide$country)), function(x) {
  colMeans(dat_wide[dat_wide$country == x, c("ha", "prod", "yield")])
})
  • Follow along, dplyr

Plotting

  • Follow along, plotting
    • Maize yield by year for South Africa
      • Base
      • ggplot
    • Graphical SAC: maize yield by country by year
      • Base
      • ggplot
    • Graphical SAC: different quantities by country year, each quantity on its own panel
      • Back to long
      • ggplot
      • How do you reconcile scales?

Regression

  • Follow along
    • Calculate and evaluate maize yield trend across time for Zambia
    • Plot the regression, base and ggplot