dplyr IBy the end of the lecture, you will be able to …
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”.
Load the standard packages and our new summarytools() package.
Load the 2024 GSS data & all survey waves.
Use the gss_which_years() function to identify the survey years a variable appeared.
# 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)
Which survey years did the variable childs appear?
A property is assigned to objects that determines how generic functions operate with it.
Common ‘types’ or ‘classes’ of variables:
class()factors consist of character data with a fixed and known set of possible values
[1] "factor"
[1] "hate" "dislike" "like"
Use a function: as.logical(), as.numeric(), as.integer(), or as.character().
When you import data into R from software like SPSS, Stata, or SAS, you might notice a special class called haven_labelled.
It makes data easier to understand without needing a separate codebook.
[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
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
1. Use zap_missing() to get rid of all the ‘missing’ (NA) levels
2. Use as_factor() to apply the labels instead of numeric values
Use zap_missing(), as_factor(), & droplevels() on the variable sex.
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.
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
Use freq() on the variable 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
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 % % Cum.
------------ ------ -------- --------
male 1787 45.17 45.17
female 2169 54.83 100.00
Total 3956 100.00 100.00
Make a pretty frequency table for the variable premarsx.
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.
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…
To run freq() by group, pair it with the stby() function.
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.
ctable()Use summarytools::ctable instead!
table() to ctable().
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%)
---------------------- ----- --------------- --------------- ---------------
Based on your table, what percentage of respondents believe sex before marriage is ‘almost always wrong’?
Based on your table, do a greater percentage of men or women think sex before marriage is ‘not wrong at all’?
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 packageThe dplyr package provides a complete set of functions that help you solve the most common data manipulation challenges:
function(argument)Functions are (most often) verbs, followed by what they will be applied to in parentheses:
dplyr verbs (functions) will allow you to solve the vast majority of your data manipulation challenges.
dplyr basicsThey are organized into four groups based on what they operate on: rows, columns, groups, or tables.
The verbs all have in common:
|>The pipe operator passes what comes before it into the function that comes after it as the first argument.
dplyr() in actionCreate a frequency table for childs variable.
dplyr grammar, starting with the name of the df and a pipe
freq() function as usual
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
Use a |> & gss_which_years() to find out which survey years the variable agekdbrn appears.
dplyr styleIn data transformation pipelines, always use a
|>|>We’ll talk about data visualization pipes later…
Heads Up!
|> (native pipe operator) and %>% (magrittr package) behave identically for simple cases. More info.
dplyr grammarWhat’s the advantage of dplyr grammar? We can sequence data manipulation!
filter() & drop_na()Use filter() to keep rows that meet a condition.
Use drop_na() to remove rows with missing (NA) values.
gss_all data frame:
# A tibble: 2 × 2
sex n
<dbl+lbl> <int>
1 1 [male] 1031
2 2 [female] 1363
Limit the dataframe to only the 2024 respondents without missing data for sex, hrs1, and childs. How many men and women are left?
na.rm is a logical evaluating to TRUE or FALSE indicating whether NA values should be stripped before the computation proceeds.
[1] 23
Min. 1st Qu. Median Mean 3rd Qu. Max. NAs
9.00 20.00 23.00 24.14 28.00 97.00 46832
Find the mean and median for the variable: hrs1.
summarize()Use functions inside summarize() to create summary variables.
dplyrUse dplyr grammar to find the frequency, mean, and median.
Add lots of summary variables using functions inside summarize().
n() function to create a count variable (no variable in parentheses)
median() function on a variable
mean() function on a variable
# A tibble: 1 × 3
freq med avg
<int> <dbl> <dbl>
1 28867 23 24.1
Use dplyr grammar to find the frequency, mean, and median for the variable: hrs1.
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 data frame:
# A tibble: 2 × 2
sex avg
<dbl+lbl> <dbl>
1 1 [male] 25.7
2 2 [female] 23.0
Compare the median and average work hours (hrs1) for U.S. men and women.
summarize() + variability measures# 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
How did the mean and standard deviation of weekly work hours differ between men and women in 2024, and what do these differences suggest about gender-based variability in labor patterns?
How do we find out?
Can you produce this table?
# A tibble: 2 × 3
`as_factor(sex)` mean sd
<fct> <dbl> <dbl>
1 male 41.7 13.7
2 female 37.3 13.7
What’s your conclusion to our research question?