<p>Recently, I have been following the development and release of Kyle Walker’s <a href="https://github.com/walkerke/tidycensus">tidycensus</a> package. I have been filled with amazement, delight, and well, perhaps another feeling…</p>
<blockquote class="twitter-tweet">
<p lang="en" dir="ltr">
There should be a word for “the regret felt when an R 📦, which would have saved untold hours of your life, is released”… <a href="https://twitter.com/hashtag/rstats?src=hash">#rstats</a> 🤔 <a href="https://t.co/2THN4MwedO">https://t.co/2THN4MwedO</a>
</p>
— Mara Averick (<span>@dataandme</span>) <a href="https://twitter.com/dataandme/status/869968290688376832">May 31, 2017</a>
</blockquote>
<p>But seriously, I have worked with US Census data a lot in the past and this package</p>
<ul>
<li>is such a valuable addition to the R ecosystem and</li>
<li>would have saved me SO MUCH ENERGY, HEADACHE, and TIME.</li>
</ul>
<p>I was working this weekend on a side project with an old friend about opioid usage in Texas and needed to download some Census data again. A perfect opportunity to give this new package a little run-through!</p>
<div>
<h2>Exercising my joygret</h2>
<p>Before running code like the following from tidycensus, you need to <a href="http://api.census.gov/data/key_signup.html">obtain an API key</a> from the Census and then use the function <code>census_api_key()</code> to set it in R.</p>
<pre><code>library(tidyverse)
library(tidycensus)

texas_pop &lt;- get_acs(geography = &quot;county&quot;, 
                     variables = &quot;B01003_001&quot;, 
                     state = &quot;TX&quot;,
                     geometry = TRUE) 

texas_pop</code></pre>
<pre><code>## Simple feature collection with 254 features and 5 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -106.6456 ymin: 25.83738 xmax: -93.50829 ymax: 36.5007
## epsg (SRID):    4269
## proj4string:    +proj=longlat +datum=NAD83 +no_defs
## # A tibble: 254 x 6
##    GEOID                    NAME   variable estimate   moe               geometry
##    &lt;chr>                   &lt;chr>      &lt;chr>    &lt;dbl> &lt;dbl> &lt;S3: sfc_MULTIPOLYGON>
##  1 48007   Aransas County, Texas B01003_001    24292     0 &lt;S3: sfc_MULTIPOLYGON>
##  2 48025       Bee County, Texas B01003_001    32659     0 &lt;S3: sfc_MULTIPOLYGON>
##  3 48035    Bosque County, Texas B01003_001    17971     0 &lt;S3: sfc_MULTIPOLYGON>
##  4 48067      Cass County, Texas B01003_001    30328     0 &lt;S3: sfc_MULTIPOLYGON>
##  5 48083   Coleman County, Texas B01003_001     8536     0 &lt;S3: sfc_MULTIPOLYGON>
##  6 48091     Comal County, Texas B01003_001   119632     0 &lt;S3: sfc_MULTIPOLYGON>
##  7 48103     Crane County, Texas B01003_001     4730     0 &lt;S3: sfc_MULTIPOLYGON>
##  8 48139     Ellis County, Texas B01003_001   157058     0 &lt;S3: sfc_MULTIPOLYGON>
##  9 48151    Fisher County, Texas B01003_001     3858     0 &lt;S3: sfc_MULTIPOLYGON>
## 10 48167 Galveston County, Texas B01003_001   308163     0 &lt;S3: sfc_MULTIPOLYGON>
## # ... with 244 more rows</code></pre>
<p>There we go! The total population in each county in Texas, in a tidyverse-ready data frame. If you want to get information for multiple states, <a href="https://walkerke.github.io/2017/05/tidycensus-every-tract/">just use purrr</a>. The US Census tabulates lots of <a href="https://www.census.gov/programs-surveys/acs/guidance/subjects.html">important kinds of information</a> here in the United States, although there has been troubling <a href="https://www.theatlantic.com/politics/archive/2017/05/census-director-resigns-2020-funding-concern/526107/">uncertainty</a> about <a href="https://www.washingtonpost.com/local/social-issues/us-census-director-resigns-amid-turmoil-over-funding-of-2020-count/2017/05/09/8f8657c6-34ea-11e7-b412-62beef8121f7_story.html">leadership and funding</a> there in recent months.</p>
<p>So we have this data in a form that will be easy to manipulate; what if we want to map it? Kyle Walker again has this taken care of, with his tigris package (a dependency of tidycensus); if you set <code>geometry = TRUE</code> the way that I did when I downloaded the Census data above, tigris handles downloading the shapefiles from the Census, with support for <code>sf</code> <a href="https://github.com/edzer/sfr">simple features</a>. Kyle has a vignette for <a href="https://walkerke.github.io/tidycensus/articles/spatial-data.html">mapping using ggplot2</a>, but you can also pipe straight into leaflet.</p>
<pre><code>library(leaflet)
library(stringr)
library(sf)

pal &lt;- colorQuantile(palette = &quot;viridis&quot;, domain = texas_pop$estimate, n = 10)

texas_pop %>%
    st_transform(crs = &quot;+init=epsg:4326&quot;) %>%
    leaflet(width = &quot;100%&quot;) %>%
    addProviderTiles(provider = &quot;CartoDB.Positron&quot;) %>%
    addPolygons(popup = ~ str_extract(NAME, &quot;^([^,]*)&quot;),
                stroke = FALSE,
                smoothFactor = 0,
                fillOpacity = 0.7,
                color = ~ pal(estimate)) %>%
    addLegend(&quot;bottomright&quot;, 
              pal = pal, 
              values = ~ estimate,
              title = &quot;Population percentiles&quot;,
              opacity = 1)</code></pre>
<div></div>
<p>What is that <code>st_transform</code> doing? Well, I am no cartographer and I am still fuzzy on these issues, but it is doing a projection onto a certain reference system of the spatial information contained in the <code>sf</code> column. The specific choice of an <a href="https://gis.stackexchange.com/questions/3334/what-is-the-difference-between-wgs84-and-epsg4326">EPSG code of 4326</a> is for a given projection.</p>
</div>
<div>
<h2>A couple more examples</h2>
<p>Let’s look at the counties in Utah (where I live) while we’re at it. Let’s map color to population here, instead of quantiles, just for something different.</p>
<pre><code>utah_pop &lt;- get_acs(geography = &quot;county&quot;, 
                    variables = &quot;B01003_001&quot;, 
                    state = &quot;UT&quot;,
                    geometry = TRUE)

pal &lt;- colorNumeric(palette = &quot;plasma&quot;, 
                    domain = utah_pop$estimate)

utah_pop %>%
    st_transform(crs = &quot;+init=epsg:4326&quot;) %>%
    leaflet(width = &quot;100%&quot;) %>%
    addProviderTiles(provider = &quot;CartoDB.Positron&quot;) %>%
    addPolygons(popup = ~ str_extract(NAME, &quot;^([^,]*)&quot;),
                stroke = FALSE,
                smoothFactor = 0,
                fillOpacity = 0.7,
                color = ~ pal(estimate)) %>%
    addLegend(&quot;bottomright&quot;, 
              pal = pal, 
              values = ~ estimate,
              title = &quot;County Populations&quot;,
              opacity = 1)</code></pre>
<div></div>
<p>Yep, that is right, although still remarkable to me. Utah is largely an extremely rural state, with lots of people here in Salt Lake City where I live and then in the corridor to the north and south.</p>
<p>There is so much other information available from the Census. For example, what if I want to look at the median home value in Salt Lake County, at the census tract level?</p>
<pre><code>slc_value &lt;- get_acs(geography = &quot;tract&quot;, 
                    variables = &quot;B25077_001&quot;, 
                    state = &quot;UT&quot;,
                    county = &quot;Salt Lake County&quot;,
                    geometry = TRUE)

pal &lt;- colorNumeric(palette = &quot;viridis&quot;, 
                    domain = slc_value$estimate)

slc_value %>%
    st_transform(crs = &quot;+init=epsg:4326&quot;) %>%
    leaflet(width = &quot;100%&quot;) %>%
    addProviderTiles(provider = &quot;CartoDB.Positron&quot;) %>%
    addPolygons(popup = ~ str_extract(NAME, &quot;^([^,]*)&quot;),
                stroke = FALSE,
                smoothFactor = 0,
                fillOpacity = 0.7,
                color = ~ pal(estimate)) %>%
    addLegend(&quot;bottomright&quot;, 
              pal = pal, 
              values = ~ estimate,
              title = &quot;Median Home Value&quot;,
              labFormat = labelFormat(prefix = &quot;$&quot;),
              opacity = 1)</code></pre>
<div></div>
<p>The two census tracts with <code>NA</code> values are the airport on the west side and the University of Utah on the east side. You can very obviously see the east-to-west gradient that comes as no surprise to us locals, and that priciest tract is up against one of the canyons with beautiful views. But mainly please notice with what ease I made this interactive map!</p>
</div>
<div>
<h2>The End</h2>
<p>Maybe the main reason I wrote up this blog post is to say how streamlined and easy it now is to get Census data into R and plot it, but another reason is to demonstrate, at least to myself, how little effort it takes to make a blog post with, say, interactive leaflet components with my new blogging workflow. I recently changed my blog from a Jekyll blog hosted on GitHub Pages to a blog built with <a href="https://github.com/rstudio/blogdown">blogdown</a> and <a href="https://gohugo.io/">Hugo</a>, deployed using <a href="https://www.netlify.com/">Netlify</a>. I am finding this workflow so great, and this post with its leaflet maps went off without a hitch! I would like to say a big THANK YOU to Yihui Xie for his work on R Markdown, knitr, and blogdown. Let me know if you have any questions!</p>
</div>