video

Turn an R Markdown document into an interactive experience

Supercharge your R code's interactivity with R Markdown and runtime Shiny

1 2 Page 2
Page 2 of 2

Instructions and code to create a data frame of data by ZIP code

if(!require("pacman")){
install.packages("pacman")
}
pacman::p_load(dplyr, tidycensus, leaflet, readr, sf, tmap,
tmaptools, choroplethrZip, tidyr, scales)
# You need a U.S. Census Bureau key. See help("census_api_key",
package = "tidycensus") for more info.
# Get zip code data for all of the U.S.
zip_data <- get_acs(geography = "zcta",
variables = c(medincome = "B19013_001", medmonthlyhousingcost = "B25105_001", pop = "B01003_001"), geometry = TRUE)
# I usually save this so I don't have to keep asking for it
save(zip_data, file = "zip_data.Rdata")
# Reshape the zipcode data from long to wide
# This will take some time to run
zip_data_wide <- zip_data %>%
select(GEOID, variable, estimate, geometry) %>%
tidyr::spread("variable", "estimate")
# I'm using old ZIP code data from 2012 to get info since this is for demo purposes.
# http://federalgovernmentzipcodes.us/
# For newer data that requires attribution, check out
# https://simplemaps.com/data/us-zips
zipcode_meta12 <- readr::read_csv("data/free-zipcode-database-Primary.csv")
# This creates a data frame for the US with the Census data and ZIP code meta data
appdata_for_map <- tmaptools::append_data(zip_data_wide, zipcode_meta12, "GEOID", "Zipcode")
# I save this, too, since it can take awhile to re-create
save(appdata_for_map, file = "appdata_for_map.Rdata")
# Now I'm filtering just for Massachusetts, and putting city names in title case. You can filter for the state of your choice
ma_appdata_for_map <- appdata_for_map %>%
filter(State == "MA") %>%
mutate(
City = tolower(City),
City = tools::toTitleCase(City)
)
# Here I'm adding more info about ZIP codes from the choroplethrZip package to my Massachusetts data with a left join.
data("zip.regions")
ma_appdata_for_map <- left_join(ma_appdata_for_map, zip.regions, by = c("GEOID" = "region")) %>%
mutate(
county.name = tools::toTitleCase(county.name)
) %>%
# This changes the map projection to what the leaflet package needs
sf::st_transform(4326) %>%
# And here I am adding some columns with nice formatting to display when I'm using map pop-ups
mutate(
income = scales::comma(medincome, prefix = "$"),
housing = scales::comma(medmonthlyhousingcost, prefix = "$"),
Pop = scales::comma(pop)
)
# Saving this too because I save everything, but you don't have to.
saveRDS(ma_appdata_for_map, file = "zip_mass_appdata_for_map.rds")
# Here's the final Massachusetts data frame for everything but the map:
markdowndata <- ma_appdata_for_map %>%
as.data.frame() %>%
select(ZipCode = GEOID, City, County = county.name, MedianHouseholdIncome = medincome, MedianMonthlyHousingCost = medmonthlyhousingcost, Population = pop)
save(markdowndata, file = "mamarkdowndata.rdata")



Copyright © 2019 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2