<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/data-acquisition-in-r-34/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://ikashnitsky.github.io/2017/data-acquisition-three/"> Ilya Kashnitsky</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>R is an incredible tool for reproducible research. In the present series of blog posts I want to show how one can easily acquire data within an R session, documenting every step in a fully reproducible way. There are numerous data acquisition options for R users. Of course, I do not attempt to show all the data possibilities and tend to focus mostly on demographic data. If your prime interest lies outside human population statistics, it’s worth checking the amazing <a rel="nofollow" href="https://github.com/ropensci/opendata" target="_blank">Open Data Task View</a>.</p>
<p>The series consists of four posts:</p>
<ul>
<li><a rel="nofollow" href="https://ikashnitsky.github.io/2017/data-acquisition-one/" target="_blank">Loading prepared datasets</a></li>
<li><a rel="nofollow" href="https://ikashnitsky.github.io/2017/data-acquisition-two" target="_blank">Accessing popular statistical databases</a></li>
<li><strong>Demographic data sources</strong></li>
<li>Getting spatial data</li>
</ul>
<p>For each of the data acquisition options I provide a small visualization use case.</p>
<h1>Human Mortality Database</h1>
<p>When it comes to testing the big questions of human population dynamics, there is no more reliable data source than <a rel="nofollow" href="http://www.mortality.org/" target="_blank">Human Mortality Database</a>. This database is run by demographers who use state-of-the-art methodology to overcome issues in the data. As the result, the estimates are as precise as possible. Their <a rel="nofollow" href="http://www.mortality.org/Public/Docs/MethodsProtocol.pdf" target="_blank">methods protocol</a> is a masterpiece of demographic data processing. On the down side, the data of decent enough quality is available for only a bunch of countries. To explore the data I highly recommend [Human Mortality Database Explorer][exp] by <a rel="nofollow" href="https://twitter.com/jschoeley" target="_blank">Jonas Schöley</a>.</p>
<p>Thanks to <a rel="nofollow" href="https://twitter.com/timriffe1" target="_blank">Tim Riffe</a>’s <code>HMDHFDplus</code> package, one can now download HMD data with just a couple of lines of <code>R</code> code. Please note that an account at <a rel="nofollow" href="http://www.mortality.org/" target="_blank">mortality.org</a> is needed in order to download data. As one may guess from the package name, it also helps to grab data from equally brilliant <a rel="nofollow" href="http://www.humanfertility.org/" target="_blank">Human Fertility Database</a>.</p>
<p>The following example is taken from my <a rel="nofollow" href="https://ikashnitsky.github.io/2017/hmd-all-sex-ratio/" target="_blank">earlier post</a> (and updated a bit). I think it illustrates nicely the power of automated data acquisition in <code>R</code>. Here I am going to download one year population population structures for both males and females for each single country of HMD. If you want to reproduce the result, beware that the script will download a couple of dozens megabits of data. Then I will calculate and visualize as small multiples sex ratios in all countries along age dimension. Sex ratios reflect the two basic regularities of human demographics: 1) there are always more boys being born; 2) males experience higher mortality throughout their life-course. Besides some artificial and well known exceptions, sex ratio at birth does not vary dramatically and is more or less constant at the level of 105-106 boys per 100 girls. Hence, differences in the sex ratio profiles of countries mainly reflect gender gap in mortality.</p>
<div>
<div>
<pre><code># load required packages
library(HMDHFDplus)
library(tidyverse)
library(purrr)


# help function to list the available countries
country &lt;- getHMDcountries()

# remove optional populations
opt_pop &lt;- c(&quot;FRACNP&quot;, &quot;DEUTE&quot;, &quot;DEUTW&quot;, &quot;GBRCENW&quot;, &quot;GBR_NP&quot;)
country &lt;- country[!country %in% opt_pop]

# temporary function to download HMD data for a simgle county (dot = input)
tempf_get_hmd &lt;- . %>% readHMDweb(&quot;Exposures_1x1&quot;, ik_user_hmd, ik_pass_hmd) 


# download the data iteratively for all countries using purrr::map()
exposures &lt;- country %>% map(tempf_get_hmd)

# data transformation to apply to each county dataframe
tempf_trans_data &lt;- . %>% 
        select(Year, Age, Female, Male) %>% 
        filter(Year %in% 2012) %>%
        select(-Year) %>%
        transmute(age = Age, ratio = Male / Female * 100)

# perform transformation
df_hmd &lt;- exposures %>% 
        map(tempf_trans_data) %>% 
        bind_rows(.id = &quot;country&quot;)

# summarize all ages older than 90 (too jerky)
df_hmd_90 &lt;- df_hmd %>% 
        filter(age %in% 90:110) %>% 
        group_by(country) %>% 
        summarise(ratio = ratio %>% mean(na.rm = T)) %>%
        ungroup() %>% 
        transmute(country, age = 90, ratio)

# insert summarized 90+
df_hmd_fin &lt;- bind_rows(df_hmd %>% filter(!age %in% 90:110), df_hmd_90)

# finaly - plot
df_hmd_fin %>%  
        ggplot(aes(age, ratio, color = country, group = country))+
        geom_hline(yintercept = 100, color = &quot;grey50&quot;, size = 1)+
        geom_line(size = 1)+
        scale_y_continuous(limits = c(0, 120), 
                           expand = c(0, 0), 
                           breaks = seq(0, 120, 20))+
        scale_x_continuous(limits = c(0, 90), 
                           expand = c(0, 0), 
                           breaks = seq(0, 80, 20))+
        facet_wrap(~country, ncol = 6)+
        theme_minimal(base_family = &quot;mono&quot;, base_size = 15)+
        theme(legend.position = &quot;none&quot;,
              panel.border = element_rect(size = .5, fill = NA, 
                                          color = &quot;grey50&quot;))+
        labs(x = &quot;Age&quot;, 
             y = &quot;Sex ratio, males per 100 females&quot;, 
             title = &quot;Sex ratio in all countries from Human Mortality Database&quot;,
             subtitle = &quot;HMD 2012, via HMDHFDplus by @timriffe1&quot;,
             caption = &quot;ikashnitsky.github.io&quot;)

</code></pre>
</div>
</div>
<p><a rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/171210/hmd.png?ssl=1" target="_blank"><img alt="fig1" src="https://i1.wp.com/ikashnitsky.github.io/images/171210/hmd.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<h1>United Nations World Population Prospects</h1>
<p>Population Department of the United Nations provides high quality population estimates for all countries of the world. They update estimates every 2-3 years and publish openly as an interactive report <a rel="nofollow" href="https://esa.un.org/unpd/wpp/" target="_blank">World Population Prospects</a>. One may find in these reports key highlights and, of course, rich data. The data is later wrapped in <code>R</code> packages called <code>wpp20xx</code>. Currently, the available packages are for the estimate updates 2008, 2010, 2012, 2015, and 2017. I will give here an example of <code>wpp2015</code> use adapted from my earlier <a rel="nofollow" href="https://ikashnitsky.github.io/2017/global-male-life-expectancy-convergence/" target="_blank">post</a>.</p>
<p>Using ridgeplot, the amazing type of dataviz promoted <code>ggridges</code> package by <a rel="nofollow" href="https://twitter.com/ClausWilke" target="_blank">Claus Wilke</a>, I am going to show the impressive reduction of global inequality in male mortality that took place since 1950.</p>
<div>
<div>
<pre><code>library(wpp2015)
library(tidyverse)
library(ggridges)
library(viridis)

# get the UN country names
data(UNlocations)

countries &lt;- UNlocations %>% pull(name) %>% paste

# data on male life expectancy at birth
data(e0M) 

e0M %>% 
        filter(country %in% countries) %>% 
        select(-last.observed) %>% 
        gather(period, value, 3:15) %>% 
        ggplot(aes(x = value, y = period %>% fct_rev()))+
        geom_density_ridges(aes(fill = period))+
        scale_fill_viridis(discrete = T, option = &quot;B&quot;, direction = -1, 
                           begin = .1, end = .9)+
        labs(x = &quot;Male life expectancy at birth&quot;,
             y = &quot;Period&quot;,
             title = &quot;Global convergence in male life expectancy at birth since 1950&quot;,
             subtitle = &quot;UNPD World Population Prospects 2015 Revision, via wpp2015&quot;,
             caption = &quot;ikashnitsky.github.io&quot;)+
        theme_minimal(base_family =  &quot;mono&quot;)+
        theme(legend.position = &quot;none&quot;)

</code></pre>
</div>
</div>
<p><a rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/171210/wpp2015.png?ssl=1" target="_blank"><img alt="fig2" src="https://i2.wp.com/ikashnitsky.github.io/images/171210/wpp2015.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<h1>European Social Survey (ESS)</h1>
<p><a rel="nofollow" href="http://www.europeansocialsurvey.org/about/" target="_blank">European Social Survey</a> provides uniquely rich nationally representative cross-county comparable information on the values of Europeans. Every two years a cross-sectional sample is taken in each participating country. All the data is easily available <a rel="nofollow" href="http://www.europeansocialsurvey.org/user/new" target="_blank">upon registration</a>. Datasets are distributed as SAS, SPSS, or STATA files. Thanks to <a rel="nofollow" href="https://twitter.com/cimentadaj" target="_blank">Jorge Cimentada</a>, these datasets are now easily available via <code>ess</code> package. I am going to visualize how respondents assessed their level of trust in police in all available countries at the latest round of the survey.</p>
<div>
<div>
<pre><code>library(ess)
library(tidyverse) 

# help gunction to see the available countries
show_countries()

# check the available rounds for a selected country
show_country_rounds(&quot;Netherlands&quot;)

# get the full dataset of the last (8) round
df_ess &lt;- ess_rounds(8, your_email =  ik_email) 

# select a variable and calculate mean value
df_ess_select &lt;- df_ess %>% 
        bind_rows() %>% 
        select(idno, cntry, trstplc) %>% 
        group_by(cntry) %>% 
        mutate(avg = trstplc %>% mean(na.rm = T)) %>% 
        ungroup() %>% 
        mutate(cntry = cntry %>% as_factor() %>% fct_reorder(avg))

df_ess_select %>% 
        ggplot(aes(trstplc, fill = avg))+
        geom_histogram()+
        scale_x_continuous(limits = c(0, 11), breaks = seq(2, 10, 2))+
        scale_fill_gradient(&quot;Average\ntrust\nscore&quot;, 
                            low = &quot;black&quot;, high = &quot;aquamarine&quot;)+
        facet_wrap(~cntry, ncol = 6)+
        theme_minimal(base_family = &quot;mono&quot;)+
        labs(x = &quot;Trust score [0 -- 10]&quot;,
             y = &quot;# of respondents&quot;,
             title = &quot;Trust in police&quot;,
             subtitle = &quot;ESS wave 8 2017, via ess by @cimentadaj&quot;,
             caption = &quot;ikashnitsky.github.io&quot;)

</code></pre>
</div>
</div>
<p><a rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/171210/ess.png?ssl=1" target="_blank"><img alt="fig3" src="https://i1.wp.com/ikashnitsky.github.io/images/171210/ess.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<h1>American Community Survey and Census</h1>
<p>There are several packages that provide access to the US Census and ACS data. Perhaps the most convenient one is the recent <code>tidycensus</code> package by <a rel="nofollow" href="https://twitter.com/kyle_e_walker" target="_blank">Kyle Walker</a>. One extremely useful feature of this approach is the ability to download geodata along with stats in the form of simple features. Simple features, a revolutionary approach to deal with spatial data in R implemented in <code>sf</code> package by <a rel="nofollow" href="https://twitter.com/edzerpebesma" target="_blank">Edzer Pebesma</a>, allow to manage and visualize geodata tidy and efficiently. Note that in order to reproduce the following example one would have to install the development version of ggplot2.</p>
<p>Below I map median ages of census tracts population in Chicago based on the ACS estimates in 2015. To use <code>tidycensus</code>, an API key is required. API is instantly provided <a rel="nofollow" href="https://api.census.gov/data/key_signup.html" target="_blank">upon registration</a>.</p>
<div>
<div>
<pre><code>library(tidycensus)
library(tidyverse)
library(viridis)
library(janitor)
library(sf)
# to use geom_sf we need the latest development version of ggplot2
devtools::install_github(&quot;tidyverse/ggplot2&quot;, &quot;develop&quot;)
library(ggplot2)


# you need a personal API key, available free at
# https://api.census.gov/data/key_signup.html
# normally, this key is to be stored in .Renviron

# see state and county codes and names
fips_codes %>% View

# the available variables
load_variables(year = 2015, dataset = &quot;acs5&quot;) %>% View

# data on median age of population in Chicago
df_acs &lt;- get_acs(
        geography = &quot;tract&quot;,
        county = &quot;Cook County&quot;,
        state = &quot;IL&quot;,
        variables = &quot;B01002_001E&quot;,
        year = 2015,
        key = ik_api_acs,
        geometry = TRUE
) %>% clean_names()


# map the data
df_acs %>% 
        ggplot()+
        geom_sf(aes(fill = estimate %>% 
                            cut(breaks = seq(20, 60, 10))), 
                color = NA)+
        scale_fill_viridis_d(&quot;Median age&quot;, begin = .4)+
        coord_sf(datum = NA)+
        theme_void(base_family =  &quot;mono&quot;)+
        theme(legend.position = c(.15, .15))+
        labs(title = &quot;Median age of population in Chicago\nby census tracts\n&quot;,
             subtitle = &quot;ACS 2015, via tidycensus by @kyle_e_walker&quot;,
             caption = &quot;ikashnitsky.github.io&quot;, 
             x = NULL, y = NULL)
</code></pre>
</div>
</div>
<p><a rel="nofollow" href="https://i0.wp.com/ikashnitsky.github.io/images/171210/tidycensus.png?ssl=1" target="_blank"><img alt="fig4" src="https://i0.wp.com/ikashnitsky.github.io/images/171210/tidycensus.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<h1>Full reproducibility</h1>
<p>All the code chunks together can be found in <a rel="nofollow" href="https://gist.github.com/ikashnitsky/2e4bb16e097b1a264eeeae13ca6d7ce3" target="_blank">this gist</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ikashnitsky.github.io/2017/data-acquisition-three/"> Ilya Kashnitsky</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/OIVC2jre8m4" height="1"></a></div>