<p>This is another post of my series about how my packages integrate into a pipe-friendly workflow. The post focusses <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=sjmisc">on my sjmisc-package</a>, which was just updated on CRAN, and highlights some of the new features. Examples are based on data from the <a target="_blank" rel="nofollow" href="http://www.europeansocialsurvey.org/">European Social Survey</a>, which are freely available.</p>
<h1>Steps of the data analysis process</h1>
<p>Let’s recall the <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/2016/11/14/pipe-friendly-workflow-with-sjplot-sjmisc-and-sjstats-part-1-rstats-tidyverse/">last post</a>, where I showed a figure from Hadley Wickham’s <a target="_blank" rel="nofollow" href="http://r4ds.had.co.nz/">R for Data Science</a> book:</p>
<figure data-shortcode="caption" class="wp-caption"><a target="_blank" rel="nofollow" href="https://i1.wp.com/strengejacke.files.wordpress.com/2016/11/data-science-explore.png?ssl=1"><img sizes="(max-width: 517px) 100vw, 517px" data-image-description="" data-orig-file="https://i1.wp.com/strengejacke.files.wordpress.com/2016/11/data-science-explore.png?w=456&amp;ssl=1" data-orig-size="517,190" data-image-title="data-science-explore" data-comments-opened="1" class="wp-image-1164" data-recalc-dims="1" data-attachment-id="1164" data-permalink="https://strengejacke.wordpress.com/2016/11/14/pipe-friendly-workflow-with-sjplot-sjmisc-and-sjstats-part-1-rstats-tidyverse/data-science-explore/" alt="(Source: http://r4ds.had.co.nz/explore-intro.html)" data-medium-file="https://i1.wp.com/strengejacke.files.wordpress.com/2016/11/data-science-explore.png?w=456&amp;ssl=1?w=300" data-large-file="https://i1.wp.com/strengejacke.files.wordpress.com/2016/11/data-science-explore.png?w=456&amp;ssl=1?w=517" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i1.wp.com/strengejacke.files.wordpress.com/2016/11/data-science-explore.png?w=456&ssl=1"></a><br>
<figcaption class="wp-caption-text">(Source: <a target="_blank" rel="nofollow" href="http://r4ds.had.co.nz/explore-intro.html">http://r4ds.had.co.nz/explore-intro.html</a>)</figcaption>
</figure>
<p>Tidying up, transforming and exploring data is an important part of data analysis, and you can manage many common tasks in this process with <a target="_blank" rel="nofollow" href="http://tidyverse.org/">the tidyverse-</a> or related packages. The <strong>sjmisc</strong>-package fits into this workflow, especially when you work with <em>labelled data</em> (like many public use data sets, and the European Social Survey as well), because it offers functions for data transformation and labelled data utility functions. This is what I’m going to show next, based on some „real life“ initial steps when beginning with data exploration.</p>
<h1>The European Social Survey</h1>
<p>As mentioned above, data from the ESS is freely available. Following examples are based on the SPSS-dataset from the <a target="_blank" rel="nofollow" href="http://www.europeansocialsurvey.org/data/download.html?r=7">current 7th round</a>. Importing foreign data is easy in R – I think, there’s no other bigger statistical software package, which let’s you import so many data formats.</p>
<p>First, load the required packages and the SPSS-data set. Note that I use the <code>read_spss</code>-function from my <strong>sjmisc</strong>-package, which wraps the read-function from the haven-package (but it does not return labelled class vectors, for some reasons…). Since the SPSS-data is labelled, the read-function returns a <a target="_blank" rel="nofollow" href="http://strengejacke.de/sjPlot/sjmisc/">labelled data frame</a>.</p>
<pre>library(sjmisc)
library(tidyverse)
ess &lt;- read_spss(&quot;ESS7e02.sav&quot;)</pre>
<h2>frq() – printing frequency tables</h2>
<p>The first thing that may be of interest might be the response rates in each country. You can plot frequencies for <em>labelled data</em> with the <code>frq()</code>-function. This function requires either a vector or data frame as input and prints the <em>variable label</em> as first line, followed by a frequency-table with values, labels, counts and percentages of the vector.</p>
<pre>frq(ess$cntry)</pre>
<pre># Country

 val          label  frq raw.prc valid.prc cum.prc
   1        Austria 1795    4.47      4.47    4.47
   2        Belgium 1769    4.40      4.40    8.87
   3    Switzerland 1532    3.81      3.81   12.68
   4 Czech Republic 2148    5.35      5.35   18.03
   5        Germany 3045    7.58      7.58   25.60

... (omitted rows)</pre>
<h2>find_var() – finding variables in a data frame</h2>
<p>Ok, next, let’s look at the distribution of gender across countries. To compute cross tables, you can use the <code>flat_table()</code> function. It requires the data as first argument, followed by any number of variable names. But first, we need to know the name of the gender-variable. It is obviously not „gender“. This is where <code>find_var()</code> comes into play. It searches for variables in a data frame by 1) variable names, 2) variable labels, 3) value labels 4) or any combination of these. By default, it looks for variable name and labels. The function also supports regex-patterns. By default, <code>find_var()</code> returns the column-indices, but you can also print a small „summary“ with the <code>as.varlab</code>-argument.</p>
<pre># find all variables with &quot;gender&quot; in name or label
find_var(ess, &quot;gender&quot;, as.varlab = T)</pre>
<pre># A tibble: 16 × 3
   col.nr var.name                                    var.label
    &lt;int>    &lt;chr>                                        &lt;chr>
1     150  dscrgnd Discrimination of respondent's group: gender
2     213  icgndra       Interviewer code, gender of respondent
3     297     gndr                                       Gender
4     298    gndr2         Gender of second person in household
5     299    gndr3          Gender of third person in household
6     300    gndr4         Gender of fourth person in household
7     301    gndr5          Gender of fifth person in household

... (omitted rows)</pre>
<p>Ok, variable in column 297, named „gndr“, is what we are looking for.</p>
<h2>flat_table() – printing cross tables</h2>
<p>Now we can look at the distribution of gender across countries:</p>
<pre>flat_table(ess, cntry, gndr)
# flat_table also works in a pipe-workflow:
ess %>% select(cntry, gndr) %>% flat_table()</pre>
<pre>               gndr Male Female No answer
cntry                                    
Austria              853    942         0
Belgium              896    873         0
Switzerland          766    766         0
Czech Republic       998   1128         0
Germany             1545   1500         0

... (omitted rows)</pre>
<h2>get_labels() – getting value labels</h2>
<p>Next thing we want to know is where to find the educational level of participants. We know that the ESS uses the <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/International_Standard_Classification_of_Education">ISCED-classification</a>. So let’s find „isced“.</p>
<pre>find_var(ess, &quot;isced&quot;, as.varlab = T)</pre>
<pre># A tibble: 4 × 3
  col.nr var.name                                        var.label
   &lt;int>    &lt;chr>                                            &lt;chr>
1    355   eisced           Highest level of education, ES - ISCED
2    447  eiscedp Partner's highest level of education, ES - ISCED
3    496  eiscedf  Father's highest level of education, ES - ISCED
4    526  eiscedm  Mother's highest level of education, ES - ISCED</pre>
<p>ISCED has several categories, but we just want three groups of educational level: low, intermediate and high. So we first need some more information about <em>eisced</em> and its coding. You can get value labels with the <code>get_labels()</code>-function. The simple function call returns the value labels of a variable as character vector, but in this case we also use <code>include.values = &quot;p&quot;</code> to see the related values of the label, and <code>drop.unused = T</code> to drop all labels of those values that don’t occur in the vector.</p>
<pre>get_labels(ess$eisced, 
           include.values = &quot;p&quot;, 
           drop.unused = T)</pre>
<pre>[1] &quot;[1] ES-ISCED I , less than lower secondary&quot;             
[2] &quot;[2] ES-ISCED II, lower secondary&quot;                       
[3] &quot;[3] ES-ISCED IIIb, lower tier upper secondary&quot;          
[4] &quot;[4] ES-ISCED IIIa, upper tier upper secondary&quot;          
[5] &quot;[5] ES-ISCED IV, advanced vocational, sub-degree&quot;       
[6] &quot;[6] ES-ISCED V1, lower tertiary education, BA level&quot;    
[7] &quot;[7] ES-ISCED V2, higher tertiary education, >= MA level&quot;
[8] &quot;[55] Other&quot;</pre>
<h2>rec() – recoding variables</h2>
<p>We just want three categories. The ISCED-classification can be recoded into lower, intermediate and higher educational levels by combining categories 1 and 2, 3 to 5 and 6 and 7. All other values (in the above example, we have a „55“ for „Other“) should be set to missing. We can easily recode and label vectors with the <code>rec()</code>-function. This function does not only recode vectors, it also allows direct labelling of categories inside the recode-syntax (this is optional, you can also use the <code>val.labels</code>-argument). We now recode <em>eisced</em> into a new variable <em>education</em>.</p>
<pre># ok, let's recode
ess$education &lt;- rec(
  ess$eisced,
  recodes = c(&quot;1:2=1 [low]; 3:5=2 [intermediate]; 6:7=3 [high]; else=NA&quot;),
  var.label = &quot;Educational level (eisced)&quot;
)
# print frequencies
frq(ess$education)</pre>
<pre># Educational level (eisced)

 val        label   frq raw.prc valid.prc cum.prc
   1          low 10845   26.99     27.17   27.17
   2 intermediate 19978   49.72     50.05   77.21
   3         high  9096   22.64     22.79  100.00
   4           NA   266    0.66        NA      NA</pre>
<p>You can see the the vector <em>education</em> has a variable label (Educational level (eisced)), which was set inside the <code>rec()</code>-function, as well as three values with labels („low“, „intermediate“ and „high“). All values 1 to 2 of <em>eisced</em> were recoded into 1 in <em>education</em>, values 3 to 5 into 2 and so on. All remaining values are set to missing (<code>else=NA</code> – for details on the recode-syntax, see <code>?rec</code>).</p>
<h2>Grouped data frames and sjmisc-package</h2>
<p>Now, how is education distributed by gender? We can group the ESS-data and print frequencies using the <code>frq()</code>-function for this as well, as this function also accepts grouped data frames. Frequencies for grouped data frames first print the group-details (variable name and category), followed by the frequency table. Thanks to labelled data, the output is easy to understand.</p>
<pre>ess %>% 
  select(education, gndr) %>% 
  group_by(gndr) %>% 
  frq()</pre>
<pre>Grouped by:
Gender: Male
# Educational level (eisced)

 val        label  frq raw.prc valid.prc cum.prc
   1          low 5023   26.62     26.79   26.79
   2 intermediate 9687   51.33     51.66   78.44
   3         high 4042   21.42     21.56  100.00
   4           NA  119    0.63        NA      NA


Grouped by:
Gender: Female
# Educational level (eisced)

 val        label   frq raw.prc valid.prc cum.prc
   1          low  5813   27.30     27.49   27.49
   2 intermediate 10278   48.27     48.61   76.10
   3         high  5054   23.74     23.90  100.00
   4           NA   147    0.69        NA      NA</pre>
<p>And what about education and gender across countries? But this time we would like to see the row percentages…</p>
<pre>ess %>% 
  select(gndr, cntry, education) %>% 
  group_by(gndr) %>% 
  flat_table(margin = &quot;row&quot;)</pre>
<pre>Grouped by:
Gender: Male
               education   low intermediate  high
cntry                                            
Austria                  17.86        69.21 12.93
Belgium                  33.93        44.38 21.69
Switzerland              18.19        61.39 20.42
Czech Republic           12.32        74.24 13.43
... (omitted rows)

Grouped by:
Gender: Female
               education   low intermediate  high
cntry                                            
Austria                  25.45        61.24 13.31
Belgium                  27.68        42.91 29.41
Switzerland              27.58        57.91 14.51
Czech Republic           12.41        75.36 12.23
... (omitted rows)</pre>
<h2>Nested data frames and models</h2>
<p>Next, we want to apply some basic analyses, to see the relation for self-rated health and education in different countries, adjusted for gender and age of respondents. First, we need to find the health-variable. We see that this variable starts with „very good health“ for value 1, and „very bad health“ for value 5. We can reverse this scale, to have better health with higher values, and recode this into a new variable <em>srh</em> (self-rated health):</p>
<pre># find all health-variables
find_var(ess, &quot;health&quot;, as.varlab = T)
# ok, found it. it's named &quot;health&quot;. now get coding 
# of this variable - we see that better health is
# coded with lower values
get_labels(ess$health)
# reverse the scale. there is a &quot;shortcut&quot; pattern
# for doing this: &quot;rev&quot;
ess$srh &lt;- rec(ess$health, &quot;rev&quot;)</pre>
<p>So, now we have our dependent variable <em>srh</em> and our independent variables <em>education</em>, <em>gndr</em> and <em>agea</em>.</p>
<p>Let’s get a quick impression about the relations between health and education across countries, by fitting linear models for each country. We can do this using <em>nested data frames</em> (see also <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/2016/08/01/pipe-friendly-bootstrapping-with-list-variables-in-rstats/">this post on bootstrapping with list-variables</a>). The <code>nest()</code>-function from the tidyr package can create subsets of a data frame, based on grouping criteria, and create a new list-variable, where each element itself is a data frame (so it’s nested, because we have data frames inside a data frame).</p>
<p>In the following example, we group the ESS-data by country, and „nest“ the groups. Now we get a data frame with two columns: First, the grouping variable (country) and second, the datasets (subsets) for each country as data frame, store in the list-variable „data“. The data frames in the subsets (in „data“) all contain the selected variables gndr, education, srh and agea.</p>
<pre># convert variable to labelled factor,
# because we then have the labels as
# factor levels in the output
ess$country &lt;- to_label(ess$cntry, drop.levels = T)
ess %>%
  select(country, gndr, education, srh, agea) %>%
  group_by(country) %>%
  nest()</pre>
<pre># A tibble: 21 × 2
          country                 data
           &lt;fctr>               &lt;list>
1         Austria &lt;tibble [1,795 × 4]>
2         Belgium &lt;tibble [1,769 × 4]>
3     Switzerland &lt;tibble [1,532 × 4]>
4  Czech Republic &lt;tibble [2,148 × 4]>

... (omitted rows)</pre>
<h2>spread_coef() – get back coefficients of nested models</h2>
<p>Using the <code>map()</code>-function from the purrr-package, we can iterate this list and apply any function on each data frame in the list-variable „data“. We want to apply the <code>lm()</code>-function to the list-variable, to run linear models for all country datasets. The results of these linear regressions are stored in another list-variable, „models“ (created with the <code>mutate()</code>-function). To quickly access and look at the coefficients, we can use the <code>spread_coef()</code>-function:</p>
<pre>ess$country &lt;- to_label(ess$cntry, drop.levels = T)
ess %>%
  select(country, gndr, education, srh, agea) %>%
  group_by(country) %>%
  nest() %>%
  mutate(models = purrr::map(data, ~ 
    lm(srh ~ education + gndr + agea, 
       data = .))) %>%
  spread_coef(models)</pre>
<pre># A tibble: 21 × 7
          country                 data   models `(Intercept)`         agea education         gndr
           &lt;fctr>               &lt;list>   &lt;list>         &lt;dbl>        &lt;dbl>     &lt;dbl>        &lt;dbl>
1         Austria &lt;tibble [1,795 × 4]> &lt;S3: lm>      4.682988 -0.018950774 0.1577497 -0.021005919
2         Belgium &lt;tibble [1,769 × 4]> &lt;S3: lm>      4.325110 -0.012303883 0.1697290 -0.086008553
3     Switzerland &lt;tibble [1,532 × 4]> &lt;S3: lm>      4.435222 -0.011108490 0.1437029 -0.042177216
4  Czech Republic &lt;tibble [2,148 × 4]> &lt;S3: lm>      5.094801 -0.029581163 0.1405284 -0.049518435
5         Germany &lt;tibble [3,045 × 4]> &lt;S3: lm>      4.046202 -0.014770345 0.2021526 -0.051458728
6         Denmark &lt;tibble [1,502 × 4]> &lt;S3: lm>      4.240526 -0.008165113 0.1880305 -0.115486662
7         Estonia &lt;tibble [2,051 × 4]> &lt;S3: lm>      4.098305 -0.023430708 0.2406452  0.003303693
8           Spain &lt;tibble [1,925 × 4]> &lt;S3: lm>      4.613964 -0.018838560 0.1452714 -0.169171898
9         Finland &lt;tibble [2,087 × 4]> &lt;S3: lm>      4.306064 -0.015847129 0.1823691 -0.030827809
10         France &lt;tibble [1,917 × 4]> &lt;S3: lm>      4.143245 -0.013747901 0.2183592 -0.119741127
# ... with 11 more rows</pre>
<p>Ok, we see that higher education is positively associated with higher self-rated health, while higher age is negatively correlated to higher self-rated health. What about gender? Forgot the coding of female and male…</p>
<pre>get_labels(ess$gndr, include.values = T)</pre>
<pre>     1           2           9 
&quot;Male&quot;    &quot;Female&quot; &quot;No answer&quot;</pre>
<p>Male persons seem to rate their health better than female respondents.</p>
<h2>Final words</h2>
<p>In this post, I wanted to show a „real life“ approach on exploring unknown datasets. In this example, a labelled dataset was used and shown, how you can work with labelled data in R. The <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=sjmisc">on my sjmisc-package</a> can be useful when performing data analysis, especially in the step of data transformation and exploration. A main focus of this package is to make life with labelled data and data transformation easier, and to integrate into modern workflows (like working with the pipe-operator).</p>
<p>This post demonstrated only a few of the functions the sjmisc-package offers, but I hope you got an impression of its application and functionality.</p>
<p> Tagged: <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/data-visualization/">data visualization</a>, <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/r/">R</a>, <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/rstats/">rstats</a>, <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/sjplot/">sjPlot</a>, <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/statistik/">Statistik</a>, <a target="_blank" rel="nofollow" href="https://strengejacke.wordpress.com/tag/tidyverse/">tidyverse</a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/strengejacke.wordpress.com/1204/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/strengejacke.wordpress.com/1204/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/_drF8G-cznI">