Plotting fieldwork with mapview

April 7, 2020
r sf mapview fieldwork

While I’m learning how to build a Hugo website with the blogdown package in R, I thought I’d share this code for generating an interactive leaflet map. It has a choropleth overlay representing the number of weeks of archaeological fieldwork I’ve done in each US county. To make this map, I am relying on Tim Applehans’ incredibly helpful R package mapview. Some of my experimentation with the mapview spinoff package leafpop can also be found here.

And, I guess, while I’m at it, I’m also contributing my first ever blogpost. You know, just what the world needs right now, another rand-oh whistling in the dark…

R Preamble


Data wrangling

fieldwork <- read.csv(here("data/fieldwork.csv"), stringsAsFactors = FALSE) %>% 
  select(project, state, county, year, weeks)

Out of laziness, I have violated a general law of database design, including multiple values separated by commas in a single table cell. This was for convenience, mainly, as the table is organized around fieldwork projects, which often span over multiple counties and field seasons. Fortunately, tidyr has a really helpful function separate_rows that handles these situations. I also assume for convenience that the weeks of the project are evenly divided across counties.

fieldwork <- fieldwork %>% 
  separate_rows(county, sep = ", ") %>% 
  group_by(year, project) %>%
  mutate(weeks = weeks/n()) %>% 

fieldwork <- fieldwork %>% 
  group_by(state, county) %>% 
  summarize(weeks = sum(weeks),
            project = paste("-", unique(project), collapse = "<br>"))

Now, we load a U.S. counties shapefile and join this data with fieldwork. The shapefile is loaded in as an sf object, so it plays nicely with dplyr.

counties <- USAboundaries::us_counties(states = unique(fieldwork$state)) %>% 
  select(state_abbr, name) %>% 
  rename("state" = state_abbr, "county" = name)

# join fieldwork and counties
fieldwork <- left_join(counties, fieldwork, by = c("state", "county"))

Map of fieldwork

And now for the map!

        zcol = "weeks", 
        map.types = c("CartoDB.Positron", "Stamen.Terrain", "OpenTopoMap"), 
        alpha.regions = 0.5, 
        na.color = "transparent", = "Weeks",
        popup = leafpop::popupTable(fieldwork, zcol = c("county", "project", "weeks")))

Total number of weeks of fieldwork: 96

Estimating hiking velocity with rHike

April 13, 2020
r sf gdistance rHike