Skip to content
R for the Rest of Us Logo

Mapping with R

Accessing Geospatial Data Through Packages

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

View code shown in video
library(rnaturalearth)

all_countries <-
  ne_countries()

all_countries

library(mapview)

all_countries |>
  mapview()

africa <-
  ne_countries(continent = "Africa")

africa |>
  mapview()

ukraine <-
  ne_countries(country = "Ukraine")

ukraine |>
  mapview()

library(rgeoboundaries)

all_countries_v2 <-
  geoboundaries(adm_lvl = 0)

all_countries_v2 |>
  mapview()

ukraine_v2 <-
  geoboundaries(country = "Ukraine")

ukraine_v2 |>
  mapview()

geoboundaries(
  country = "Ukraine",
  adm_lvl = 1
) |>
  mapview()

geoboundaries(
  country = "Ukraine",
  adm_lvl = 2
) |>
  mapview()

geoboundaries(
  country = "USA",
  adm_lvl = 2
) |>
  mapview()

library(tigris)

us_states <-
  states()

us_states

us_states |>
  mapview()

oregon_counties <-
  counties(state = "OR")

oregon_counties

oregon_counties |>
  mapview()

library(tidycensus)

census_api_key("YOUR API KEY GOES HERE",
               install = TRUE)

acs_variables <-
  load_variables(
    year = 2023,
    dataset = "acs5",
    cache = TRUE
  )

median_household_income <-
  get_acs(
    geography = "county",
    state = "OR",
    variable = "B19013_001"
  )

median_household_income

median_household_income_sf <-
  get_acs(
    geography = "county",
    state = "OR",
    variable = "B19013_001",
    geometry = TRUE
  )

median_household_income_sf

median_household_income_sf |>
  mapview(zcol = "estimate")

Your Turn

  1. Use the {rnaturalearth} or {rgeoboundaries} package to download data for all countries in South America

  2. Use the {mapview} package to make a map in order to ensure the data was downloaded correctly

  3. If you are in the US (or work with US data), try out downloading data using {tidycensus}

Learn More

To learn about the {rnaturalearth} package, check out its documentation website. If you want to learn more about the Natural Earth project, check out its website (here is the page on its disputed borders policy).

Info on {rgeoboundaries} can be found on GitHub.

Info on the {tigris} package is on GitHub while info on {tidycensus} can be found on its documentation website.

Kyle Walker, developer of {tigris} and {tidycensus} has a book called Analyzing US Census Data: Methods, Maps, and Models in R, which discusses how to use both packages. I interviewed Kyle for my own book, R for the Rest of Us: A Statistics-Free Introduction, and talk about {tidycensus} in Chapter 11.

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.