Learning objectives

By the end of the lecture, you will be able to …

  • identify and convert variable types
  • create useful frequency tables
  • implement some basic variable manipulation
  • produce measures of central tendency and variability

Mini-task

Install the summarytools() package, available on CRAN.


Run the code chunk in your code-along.

OR: Copy and paste the code into your Console pane. Then hit “Enter”.


install.packages("summarytools")

Mini-task

Load the standard packages and our new summarytools() package.


library(tidyverse)
library(haven) # not core tidyverse
library(gssr)
library(gssrdoc) # load the GSS codebook
library(summarytools)

Mini-task

Load the 2024 GSS data & all survey waves.


# Get the data only for the 2024 survey respondents
gss24 <- gss_get_yr(2024)

# Get the data all survey years
data(gss_all)

Use the gss_which_years() function to identify the survey years a variable appeared.


gss_which_years(gss_all, meovrwrk)
# A tibble: 35 × 2
   year      meovrwrk
   <dbl+lbl> <lgl>   
 1 1972      FALSE   
 2 1973      FALSE   
 3 1974      FALSE   
 4 1975      FALSE   
 5 1976      FALSE   
 6 1977      FALSE   
 7 1978      FALSE   
 8 1980      FALSE   
 9 1982      FALSE   
10 1983      FALSE   
# ℹ 25 more rows


Heads Up!

If run in the console, to see all rows, wrap the code in the print() command: print(gss_which_years(gss_all, meovrwrk), n = 40)

Mini-task

Which survey years did the variable childs appear?


gss_which_years(gss_all, childs)
# A tibble: 35 × 2
   year      childs
   <dbl+lbl> <lgl> 
 1 1972      TRUE  
 2 1973      TRUE  
 3 1974      TRUE  
 4 1975      TRUE  
 5 1976      TRUE  
 6 1977      TRUE  
 7 1978      TRUE  
 8 1980      TRUE  
 9 1982      TRUE  
10 1983      TRUE  
# ℹ 25 more rows

Variable Types

Data types in R

A property is assigned to objects that determines how generic functions operate with it.

Common ‘types’ or ‘classes’ of variables:

  • logical
  • character
  • integer
  • numeric
  • and more, but we won’t be focusing on those

Data class + variable type

class()

logical - Boolean values TRUE and FALSE


class(TRUE)
[1] "logical"

character - character strings



class("Sociology")
[1] "character"


Integer - numeric data without decimals
(indicated with an L).

class(2L)
[1] "integer"


numeric - default type if values are numbers or if the values contain decimals.

class(2.5)
[1] "numeric"

Factor

factors consist of character data with a fixed and known set of possible values


opinion <- factor(c("like", "dislike", "dislike", "hate", "dislike", "hate"))
class(opinion)
[1] "factor"


# By default, the levels are sorted alphabetically.
levels(opinion)
[1] "dislike" "hate"    "like"   

Factor order

# Reorder the levels with the argument `levels` in the `factor()` function
opinion <- factor(opinion, levels = c("hate", "dislike", "like"))
levels(opinion)
[1] "hate"    "dislike" "like"   


# If the order has meaning (like rankings), you can make it an ordered factor
opinion <- factor(opinion, levels = c("hate", "dislike", "like"), ordered = TRUE)
levels(opinion)
[1] "hate"    "dislike" "like"   

Converting between types

Use a function: as.logical(), as.numeric(), as.integer(), or as.character().


Create a numeric variable.

x <- 1:3
x
[1] 1 2 3
class(x)
[1] "integer"


Heads Up!

The : (colon) means ‘through.’

Change it to a character variable.

y <- as.character(x)
y
[1] "1" "2" "3"
class(y)
[1] "character"


Heads Up!

Notice the quotation marks around the values.

Haven labelled

When you import data into R from software like SPSS, Stata, or SAS, you might notice a special class called haven_labelled.


class(gss24$premarsx)
[1] "haven_labelled" "vctrs_vctr"     "double"        
table(gss24$premarsx)

   1    2    3    4 
 438  172  317 1633 

Haven labelled cont.

It makes data easier to understand without needing a separate codebook.

attr(gss24$premarsx, "label")
print_labels(gss24$premarsx)
1
A description of the variable
2
View the label attached to each numeric value
[1] "Sex before marriage"

Labels:
 value                         label
     1                  always wrong
     2           almost always wrong
     3          wrong only sometimes
     4              not wrong at all
     5                         other
 NA(d)                    don't know
 NA(i)                           iap
 NA(j)            I don't have a job
 NA(m)                   dk, na, iap
 NA(n)                     no answer
 NA(p)                 not imputable
 NA(r)                       refused
 NA(s)                skipped on web
 NA(u)                    uncodeable
 NA(x) not available in this release
 NA(y)    not available in this year
 NA(z)                  see codebook

You can use as_factor to see the value labels of the variable premarsx.

Use as_factor() inside the table() function for the variable premarsx

table(as_factor(gss24$premarsx), useNA = "ifany")

                 always wrong           almost always wrong 
                          438                           172 
         wrong only sometimes              not wrong at all 
                          317                          1633 
                        other                           iap 
                            0                          1351 
                   don't know            I don't have a job 
                           50                             0 
                  dk, na, iap                     no answer 
                            0                             6 
                not imputable                       refused 
                            0                             0 
               skipped on web                    uncodeable 
                           19                             0 
not available in this release    not available in this year 
                            0                             0 
                 see codebook 
                            0 
table(gss24$premarsx, useNA = "ifany")

   1    2    3    4 <NA> 
 438  172  317 1633 1426 

Convert labels to factors

1. Use zap_missing() to get rid of all the ‘missing’ (NA) levels


gss24$premarsx <- zap_missing(gss24$premarsx)
table(as_factor(gss24$premarsx), useNA = "ifany") # see the results

        always wrong  almost always wrong wrong only sometimes 
                 438                  172                  317 
    not wrong at all                other                 <NA> 
                1633                    0                 1426 

2. Use as_factor() to apply the labels instead of numeric values


gss24$premarsx <- as_factor(gss24$premarsx) # replace the values with labels
table(gss24$premarsx, useNA = "ifany") # notice we didn't need to wrap the variable in as_factor

        always wrong  almost always wrong wrong only sometimes 
                 438                  172                  317 
    not wrong at all                other                 <NA> 
                1633                    0                 1426 

3. Use droplevels() to get rid of the empty levels in premarsx.


gss24$premarsx <- droplevels(gss24$premarsx)
table(gss24$premarsx)

        always wrong  almost always wrong wrong only sometimes 
                 438                  172                  317 
    not wrong at all 
                1633 

Mini-task

Use zap_missing(), as_factor(), & droplevels() on the variable sex.


gss24$sex <- zap_missing(gss24$sex)
gss24$sex <- as_factor(gss24$sex)
gss24$sex <- droplevels(gss24$sex)

table(gss24$sex)
1
Get rid of all the ‘missing’ (NA) levels.
2
Replace the values with labels.
3
Get rid of the empty levels (if any).

  male female 
  1787   2169 

Frequency Distributions

Relative frequency table

Let’s try functions from the summarytools() package to get univariate (1 variable) and bivariate (2 variables) descriptive statistics.


freq() creates table of the counts for a variable.

freq(gss24$sex)
Frequencies  
gss24$sex  
Type: Factor  

               Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
------------ ------ --------- -------------- --------- --------------
        male   1787     45.17          45.17     44.83          44.83
      female   2169     54.83         100.00     54.42          99.25
        <NA>     30                               0.75         100.00
       Total   3986    100.00         100.00    100.00         100.00

Mini-task

Use freq() on the variable premarsx


freq(gss24$premarsx)
Frequencies  
gss24$premarsx  
Type: Factor  

                             Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
-------------------------- ------ --------- -------------- --------- --------------
              always wrong    438     17.11          17.11     10.99          10.99
       almost always wrong    172      6.72          23.83      4.32          15.30
      wrong only sometimes    317     12.38          36.21      7.95          23.26
          not wrong at all   1633     63.79         100.00     40.97          64.22
                      <NA>   1426                              35.78         100.00
                     Total   3986    100.00         100.00    100.00         100.00

Pretty tables

One of summarytools main purposes is to help clean and prepare data for further analysis. But sometimes we don’t care about the missing values.


Using report.nas = FALSE suppresses the missing data.
The headings = FALSE parameter suppresses the heading section.


freq(gss24$sex, report.nas = FALSE, headings = FALSE)

               Freq        %   % Cum.
------------ ------ -------- --------
        male   1787    45.17    45.17
      female   2169    54.83   100.00
       Total   3956   100.00   100.00

Mini-task

Make a pretty frequency table for the variable premarsx.


freq(gss24$premarsx, report.nas = FALSE, headings = FALSE)

                             Freq        %   % Cum.
-------------------------- ------ -------- --------
              always wrong    438    17.11    17.11
       almost always wrong    172     6.72    23.83
      wrong only sometimes    317    12.38    36.21
          not wrong at all   1633    63.79   100.00
                     Total   2560   100.00   100.00

Cross-tabs

We’ve been using the table() function with one variable at a time, but it also let’s you create a frequency table (crosstab) with two variables.


# 1st variable is the rows, 2nd variable is the columns.
table(gss24$premarsx, gss24$sex)
                      
                       male female
  always wrong          180    256
  almost always wrong    71     98
  wrong only sometimes  155    161
  not wrong at all      734    891


But it’s missing the column percentages…

Relative frequency by group

To run freq() by group, pair it with the stby() function.

stby(gss24$premarsx, gss24$sex, freq)
Frequencies  
gss24$premarsx  
Type: Factor  
Group: sex = male  

                             Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
-------------------------- ------ --------- -------------- --------- --------------
              always wrong    180     15.79          15.79     10.07          10.07
       almost always wrong     71      6.23          22.02      3.97          14.05
      wrong only sometimes    155     13.60          35.61      8.67          22.72
          not wrong at all    734     64.39         100.00     41.07          63.79
                      <NA>    647                              36.21         100.00
                     Total   1787    100.00         100.00    100.00         100.00

Group: sex = female  

                             Freq   % Valid   % Valid Cum.   % Total   % Total Cum.
-------------------------- ------ --------- -------------- --------- --------------
              always wrong    256     18.21          18.21     11.80          11.80
       almost always wrong     98      6.97          25.18      4.52          16.32
      wrong only sometimes    161     11.45          36.63      7.42          23.74
          not wrong at all    891     63.37         100.00     41.08          64.82
                      <NA>    763                              35.18         100.00
                     Total   2169    100.00         100.00    100.00         100.00


This is hard to read and we don’t need the cumulative frequencies.

Pretty cross-tabs with ctable()

Use summarytools::ctable instead!


ctable(gss24$premarsx, gss24$sex,
  prop = "c",
  format = "p",
  useNA = "no"
) 
1
Change from table() to ctable().
2
The “c” gives column %; “r” would give row %.
3
This adds the % symbols to the table.
4
Exclude the missing levels from the table.
Cross-Tabulation, Column Proportions  
premarsx * sex  
Data Frame: gss24  

---------------------- ----- --------------- --------------- ---------------
                         sex            male          female           Total
              premarsx                                                      
          always wrong          180 ( 15.8%)    256 ( 18.2%)    436 ( 17.1%)
   almost always wrong           71 (  6.2%)     98 (  7.0%)    169 (  6.6%)
  wrong only sometimes          155 ( 13.6%)    161 ( 11.5%)    316 ( 12.4%)
      not wrong at all          734 ( 64.4%)    891 ( 63.4%)   1625 ( 63.8%)
                 Total         1140 (100.0%)   1406 (100.0%)   2546 (100.0%)
---------------------- ----- --------------- --------------- ---------------

dplyr I

Tidying Data

Most tasks related to data analysis are not glorious or fancy.


A lot of time is dedicated to whipping a dataset into the shape needed to be able to analyze it.


This task has different names “data cleaning,” “data management,” “data manipulation,” “data wrangling,” “data transformation.”

dplyr package

The dplyr package provides a complete set of functions that help you solve the most common data manipulation challenges:

  • filtering observations based on their values
  • extracting observations based on their values or positions
  • sampling observations based on a specific number or fraction of rows
  • sorting observations based on one or several variables
  • selecting variables based on their names or positions
  • renaming variables
  • adding new variables based on existing ones
  • summarizing observations or variables to a single descriptive measure
  • performing any operation by grouping

function(argument)

Functions are (most often) verbs, followed by what they will be applied to in parentheses:


do_this(to_this)
do_that(to_this, to_that, with_those)


dplyr verbs (functions) will allow you to solve the vast majority of your data manipulation challenges.

dplyr basics

They are organized into four groups based on what they operate on: rows, columns, groups, or tables.


The verbs all have in common:

  1. The first argument is always a data frame.
  2. The subsequent arguments typically describe which columns to operate on using the variable names (without quotes).
  3. The output is always a new data frame.

The pipe |>

The pipe operator passes what comes before it into the function that comes after it as the first argument.


sum(1, 2)
[1] 3


1 |> 
  sum(2)
[1] 3

dplyr() in action

Create a frequency table for childs variable.

gss_all$childs <- zap_missing(gss_all$childs) 
gss_all$childs <- as_factor(gss_all$childs)   
gss_all$childs <- droplevels(gss_all$childs)  

gss_all |>
  freq(childs, report.nas = FALSE) |>
  tb()
1
Use dplyr grammar, starting with the name of the df and a pipe
2
Use the freq() function as usual
3
Add the tb() function to turn the table into a tibble

dplyr() in action

# A tibble: 9 × 4
  childs     freq    pct pct_cum
  <fct>     <dbl>  <dbl>   <dbl>
1 0         20956 27.8      27.8
2 1         11979 15.9      43.7
3 2         18989 25.2      68.9
4 3         11671 15.5      84.3
5 4          5996  7.95     92.3
6 5          2669  3.54     95.8
7 6          1381  1.83     97.7
8 7           734  0.973    98.6
9 8 or more  1032  1.37    100  

Mini-task

Use a |> & gss_which_years() to find out which survey years the variable agekdbrn appears.

gss_all |>
  gss_which_years(agekdbrn)
# A tibble: 35 × 2
   year      agekdbrn
   <dbl+lbl> <lgl>   
 1 1972      FALSE   
 2 1973      FALSE   
 3 1974      FALSE   
 4 1975      FALSE   
 5 1976      FALSE   
 6 1977      FALSE   
 7 1978      FALSE   
 8 1980      FALSE   
 9 1982      FALSE   
10 1983      FALSE   
# ℹ 25 more rows

dplyr style

In data transformation pipelines, always use a

  • space before |>
  • line break after |>
  • indent the next line of code

We’ll talk about data visualization pipes later…


Heads Up!

|> (native pipe operator) and %>% (magrittr package) behave identically for simple cases. More info.

dplyr grammar

What’s the advantage of dplyr grammar? We can sequence data manipulation!


gss_all |> 
  filter(year == 2022) |>
  drop_na(sex, agekdbrn) |>
  group_by(sex) |>
  summarize(avg = mean(agekdbrn))
# A tibble: 2 × 2
  sex          avg
  <dbl+lbl>  <dbl>
1 1 [male]    26.3
2 2 [female]  23.7

filter() & drop_na()

Use filter() to keep rows that meet a condition.
Use drop_na() to remove rows with missing (NA) values.


gss_all |>
  filter(year == 2022) |>
  drop_na(sex, agekdbrn)|>
  count(sex)
1
Start with the gss_all data frame:
2
Keep only the respondents from the 2022 survey
3
Remove any observations with missing data for our key variables
4
Tally how many complete entries remain for each gender
# A tibble: 2 × 2
  sex            n
  <dbl+lbl>  <int>
1 1 [male]    1031
2 2 [female]  1363

Mini-task

Limit the dataframe to only the 2024 respondents without missing data for sex, hrs1, and childs. How many men and women are left?

gss_all |> 
  filter(year == 2024) |> 
  drop_na(sex, hrs1, childs) |>
  count(sex)
# A tibble: 2 × 2
  sex            n
  <dbl+lbl>  <int>
1 1 [male]     859
2 2 [female]   888

Summary Statistics

Median & Mean w base R

# Using base R
median(gss_all$agekdbrn, na.rm=TRUE)
1
na.rm is a logical evaluating to TRUE or FALSE indicating whether NA values should be stripped before the computation proceeds.
[1] 23


mean(gss_all$agekdbrn, na.rm=TRUE)
[1] 24.14491


# show me summary statistics
summary(gss_all$agekdbrn)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.     NAs 
   9.00   20.00   23.00   24.14   28.00   97.00   46832 

Mini-task

Find the mean and median for the variable: hrs1.

# separately
median(gss_all$hrs1, na.rm=TRUE)
mean(gss_all$hrs1, na.rm=TRUE)

# together
summary(gss_all$hrs1)
[1] 40
[1] 41.11279
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.     NAs 
   0.00   37.00   40.00   41.11   48.00   89.00   32371 

summarize()

Use functions inside summarize() to create summary variables.


gss_all |>  
  drop_na(agekdbrn) |>
   summarize(
    avg = mean(agekdbrn)
    ) 
# A tibble: 1 × 1
    avg
  <dbl>
1  24.1

Median & Mean with dplyr

Use dplyr grammar to find the frequency, mean, and median.


Add lots of summary variables using functions inside summarize().

gss_all |>  
  drop_na(agekdbrn) |> 
  summarize(
    freq = n(),
    med = median(agekdbrn),
    avg = mean(agekdbrn)
    ) 
1
Use n() function to create a count variable (no variable in parentheses)
2
Use median() function on a variable
3
Use mean() function on a variable
# A tibble: 1 × 3
   freq   med   avg
  <int> <dbl> <dbl>
1 28867    23  24.1

Mini-task

Use dplyr grammar to find the frequency, mean, and median for the variable: hrs1.

gss_all |>  
  drop_na(hrs1) |>
   summarize(
    freq = n(),
    med = median(hrs1),
    avg = mean(hrs1)
    ) 
# A tibble: 1 × 3
   freq   med   avg
  <int> <dbl> <dbl>
1 43328    40  41.1

group_by() and summarize()

Use group_by() to organize your data into groups based on one or more variables.
Use summarize() to compute statistics like total, mean, or median for each group.

gss_all |>
  drop_na(sex, agekdbrn) |>
  group_by(sex) |>
  summarize(avg = mean(agekdbrn))
1
Start with the gss_all data frame:
2
Remove any observations with missing data for our key variables
3
Do the next steps separately for each group in the variable
4
Creates a new data frame with one row for each combination of grouping variables
# A tibble: 2 × 2
  sex          avg
  <dbl+lbl>  <dbl>
1 1 [male]    25.7
2 2 [female]  23.0

Mini-task

Compare the median and average work hours (hrs1) for U.S. men and women.

gss_all |>  
  drop_na(sex, hrs1) |> 
  group_by(sex) |> 
  summarize(
    med = median(hrs1),
    avg = mean(hrs1)
    ) 
# A tibble: 2 × 3
  sex          med   avg
  <dbl+lbl>  <dbl> <dbl>
1 1 [male]      40  44.3
2 2 [female]    40  37.8

summarize() + variability measures

gss_all |>  
  drop_na(agekdbrn, sex)  |>
  group_by(as_factor(sex)) |>  
  summarize(
    freq = n(),
    min = min(agekdbrn),
    median = median(agekdbrn),
    max = max(agekdbrn),
    mean = round(mean(agekdbrn), digits = 2), 
    sd = sd(agekdbrn)
    ) 
# A tibble: 2 × 7
  `as_factor(sex)`  freq min       median max        mean    sd
  <fct>            <int> <dbl+lbl>  <dbl> <dbl+lbl> <dbl> <dbl>
1 male             11790 9             25 65         25.7  5.85
2 female           17009 9             22 57         23.0  5.30