<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/"></div></div><div><a data-url="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/" data-counturl="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/" data-count="horizontal" data-text="Counting [U.S.] Expatriation with R (a.k.a. a Decade of Desertion)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rud.is/b/2016/08/08/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/"> R – rud.is</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>If you’re even remotely following the super insane U.S. 2016 POTUS <strike>circus</strike> election you’ve no doubt seen a resurgence of <em>“if X gets elected, I’m moving to Y”</em> claims by folks who are “anti” one candidate or another. The <a target="_blank" href="http://www.washingtonexaminer.com/americans-renouncing-citizenship-near-record-highs/article/2598074">Washington Examiner</a> did a story on last quarter’s U.S. expatriation numbers. I didn’t realize we had a department in charge of tracking and posting that data, but we do thanks to inane bureaucratic compliance laws.</p>
<p>I should have put <em>“posting that data”</em> in quotes as it’s collected quarterly and posted ~2 months later in non-uniform HTML and PDF form across individual posts in a unique/custom Federal Register publishing system. How’s that hope and change in “open government data” working out for y’all?</p>
<p>The data is organized enough that we can take a look at the history of expatriation with some help from R. Along the way we’ll:</p>
<ul>
<li>see how to make paramaterized web requests a bit cleaner with <code>httr</code></li>
<li>get even <em>more</em> practice using the <code>purrr</code> package</li>
<li>perhaps learn a new “trick” when using the <code>stringi</code> package</li>
<li>show how we can “make do” living in a non-XPath 2 world (it’s actually pretty much at XPath 3 now, too #sigh) </li>
</ul>
<p>A manual hunt on that system will eventually reveal a search URL that you can use in a <code>read.csv()</code> (to grab a list of URLs with the data, not the data itself #ugh). Those URLs are <em>gnarly</em> (you’ll see what I mean if you do the hunt) but we can take advantage of the standardized URL query parameter that are used in the egregiously long URLs in a far more readable fashion if we use <code>httr::GET()</code> directly, especially since <code>httr::content()</code> will auto-convert the resultant CSV to a <code>tibble</code> for us since the site sets the response MIME type appropriately.</p>
<p>Unfortunately, when using the <code>6039G</code> search parameter (the expatriate tracking form ID) we do need to filter out non-quarterly report documents since the bureaucrats must have their ancillary TPS reports.</p>
<pre><code>GET(&quot;https://www.federalregister.gov/articles/search.csv&quot;,
    query=list(`conditions[agency_ids][]`=254,
               `conditions[publication_date][gte]`=&quot;01/01/2006&quot;,
               `conditions[publication_date][lte]`=&quot;7/29/2016&quot;,
               `conditions[term]`=&quot;6039G&quot;,
               `conditions[type][]`=&quot;NOTICE&quot;)) %>%
  content(&quot;parsed&quot;) %>%
  filter(grepl(&quot;^Quarterly&quot;, title)) -> register

glimpse(register)
## Observations: 44
## Variables: 9
## $ citation         &lt;chr> &quot;81 FR 50058&quot;, &quot;81 FR 27198&quot;, &quot;81 FR 65...
## $ document_number  &lt;chr> &quot;2016-18029&quot;, &quot;2016-10578&quot;, &quot;2016-02312...
## $ title            &lt;chr> &quot;Quarterly Publication of Individuals, ...
## $ publication_date &lt;chr> &quot;07/29/2016&quot;, &quot;05/05/2016&quot;, &quot;02/08/2016...
## $ type             &lt;chr> &quot;Notice&quot;, &quot;Notice&quot;, &quot;Notice&quot;, &quot;Notice&quot;,...
## $ agency_names     &lt;chr> &quot;Treasury Department; Internal Revenue ...
## $ html_url         &lt;chr> &quot;https://www.federalregister.gov/articl...
## $ page_length      &lt;int> 9, 17, 16, 20, 8, 20, 16, 12, 9, 15, 8,...
## $ qtr              &lt;date> 2016-06-30, 2016-03-31, 2015-12-31, 20...</code></pre>
<p>Now, we grab the content at each of the <code>html_url</code>s and save them off to be kind to bandwidth and/or folks with slow connections (so you don’t have to re-grab the HTML):</p>
<pre><code>docs &lt;- map(register$html_url, read_html)
saveRDS(docs, file=&quot;deserters.rds&quot;)</code></pre>
<p>That generates a list of parsed HTML documents.</p>
<p>The reporting dates aren’t 100% consistent (i.e. not always “n” weeks from the collection date), but the data collection dates <em>embedded textually in the report</em> are (mostly…some vary in the use of upper/lower case). So, we use the fact that these are boring legal documents that use the same language for various phrases and extract the “quarter ending” dates so we know what year/quarter the data is relevant for:</p>
<pre><code>register %&lt;>%
  mutate(qtr=map_chr(docs, ~stri_match_all_regex(html_text(.), &quot;quarter ending ([[:alnum:], ]+)\\.&quot;,
                                                     opts_regex=stri_opts_regex(case_insensitive=TRUE))[[1]][,2]),
         qtr=mdy(qtr))</code></pre>
<p>I don’t often use that particular <code>magrittr</code> pipe, but it “feels right” in this case and is handy in a pinch.</p>
<p>If you visit some of the URLs directly, you’ll see that there are tables and/or lists of names of the expats. However, there are woefully inconsistent naming &amp; formatting conventions for these lists of names <em>and</em> (as I noted earlier) there’s no XPath 2 support in R. Therefore, we have to make a slightly more verbose XPath query to target the necessary table for scraping since we need to account for vastly different column name structures for the tables we are targeting.</p>
<p>NOTE: Older HTML pages may not have HTML tables at all and some only reference PDFs, so don’t rely on this code working beyond these particular dates (at least consistently).</p>
<p>We’ll also tidy up the data into a neat <code>tibble</code> for plotting.</p>
<pre><code>map(docs, ~html_nodes(., xpath=&quot;.//table[contains(., 'First name') or
                                         contains(., 'FIRST NAME') or
                                         contains(., 'FNAME')]&quot;)) %>%
  map(~html_table(.)[[1]]) -> tabs

data_frame(date=register$qtr, count=map_int(tabs, nrow)) %>%
  filter(format(as.Date(date), &quot;%Y&quot;) >= 2006) -> left</code></pre>
<p>With the data wrangling work out of the way, we can tally up the throngs of folks desperate for greener pastures. First, by quarter:</p>
<pre><code>gg &lt;- ggplot(left, aes(date, count))
gg &lt;- gg + geom_lollipop()
gg &lt;- gg + geom_label(data=data.frame(),
                      aes(x=min(left$date), y=1500, label=&quot;# individuals&quot;),
                      family=&quot;Arial Narrow&quot;, fontface=&quot;italic&quot;, size=3, label.size=0, hjust=0)
gg &lt;- gg + scale_x_date(expand=c(0,14), limits=range(left$date))
gg &lt;- gg + scale_y_continuous(expand=c(0,0), label=comma, limits=c(0,1520))
gg &lt;- gg + labs(x=NULL, y=NULL,
                title=&quot;A Decade of Desertion&quot;,
                subtitle=&quot;Quarterly counts of U.S. individuals who have chosen to expatriate (2006-2016)&quot;,
                caption=&quot;Source: https://www.federalregister.gov/&quot;)
gg &lt;- gg + theme_hrbrmstr_an(grid=&quot;Y&quot;)
gg</code></pre>
<p><a target="_blank" href="https://i2.wp.com/rud.is/b/wp-content/uploads/2016/08/RStudio.png?ssl=1"><img alt="RStudio" class="wp-image-4623" src="https://i2.wp.com/rud.is/b/wp-content/uploads/2016/08/RStudio.png?resize=456%2C252&ssl=1" data-recalc-dims="1"></a></p>
<p>and, then annually:</p>
<pre><code>left %>%
  mutate(year=format(date, &quot;%Y&quot;)) %>%
  count(year, wt=count) %>%
  ggplot(aes(year, n)) -> gg

gg &lt;- gg + geom_bar(stat=&quot;identity&quot;, width=0.6)
gg &lt;- gg + geom_label(data=data.frame(), aes(x=0, y=5000, label=&quot;# individuals&quot;),
                      family=&quot;Arial Narrow&quot;, fontface=&quot;italic&quot;, size=3, label.size=0, hjust=0)
gg &lt;- gg + scale_y_continuous(expand=c(0,0), label=comma, limits=c(0,5100))
gg &lt;- gg + labs(x=NULL, y=NULL,
                title=&quot;A Decade of Desertion&quot;,
                subtitle=&quot;Annual counts of U.S. individuals who have chosen to expatriate (2006-2016)&quot;,
                caption=&quot;Source: https://www.federalregister.gov/&quot;)
gg &lt;- gg + theme_hrbrmstr_an(grid=&quot;Y&quot;)
gg</code></pre>
<p><a target="_blank" href="https://i2.wp.com/rud.is/b/wp-content/uploads/2016/08/RStudio-1.png?ssl=1"><img alt="RStudio" class="wp-image-4624" src="https://i2.wp.com/rud.is/b/wp-content/uploads/2016/08/RStudio-1.png?resize=456%2C254&ssl=1" data-recalc-dims="1"></a></p>
<p>The exodus isn’t <em>massive</em> but it’s actually more than I expected. It’d be interesting to track various US tax code laws, enactment of other compliance regulations and general news events to see if there are underlying reasons for the overall annual increases but also the dips in some quarters (which could just be data collection hiccups by the Feds…after all, this is government work). If you want to do all the math for correcting survey errors, it’d also be interesting to normalize this by population and track all the data back to 1996 (when HIPPA mandated the creation &amp; publication of this quarterly list) and then see if you can predict where we’ll be at the end of this year (though I suspect political events are a motivator for at least a decent fraction of some of the quarters).</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/"></div></div><div><a data-url="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/" data-counturl="https://www.r-bloggers.com/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/" data-count="vertical" data-text="Counting [U.S.] Expatriation with R (a.k.a. a Decade of Desertion)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rud.is/b/2016/08/08/counting-u-s-expatriation-with-r-a-k-a-a-decade-of-desertion/"> R – rud.is</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/p6Nfe4XGDlo"></a></div>