-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdata-wrangling-and-analysis-solutions.Rmd
508 lines (320 loc) · 12.7 KB
/
data-wrangling-and-analysis-solutions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
---
title: "Fundamentals of Data Wrangling and Analysis Exercises"
author: "R for the Rest of Us"
output:
html_document:
css: slides/style.css
toc: true
toc_depth: 1
toc_float: true
df_print: paged
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
The exercises are part of the Fundamentals of R course. For more, see the [R for the Rest of Us website](https://rfortherestofus.com/courses/fundamentals/).
# Load Packages
Load the `tidyverse` and `janitor` packages.
```{r}
library(tidyverse)
library(janitor)
```
# Import NHANES Data
Import the NHANES data to a data frame called `nhanes`. Then, use the `clean_names` function to create clean names for all of your variables.
```{r}
nhanes <- read_csv("data/nhanes.csv") %>%
clean_names()
```
# select
![](slides/images/select.png)
With `select` we can select variables from the larger data frame.
Use `select` to show just the `marital_status` variable.
```{r}
nhanes %>%
select(marital_status)
```
We can also use `select` for multiple variables.
Use `select` to show `marital_status` and `education`.
```{r}
nhanes %>%
select(marital_status, education)
```
Used within `select`, the `contains` function selects variable with certain text in the variable name.
Use the `contains` function to select variables that ask how many days in the last 30 days the respondent had bad physical and mental health (you should be able to figure out which variables these are from the names).
```{r}
nhanes %>%
select(contains("hlth_bad"))
```
Used within `select`, the `starts_with` function selects variable with certain text in the variable name.
Use the `starts_with` function to select variables that start with the letter h.
```{r}
nhanes %>%
select(starts_with("h"))
```
We can `select` a range of columns using the var1:var2 pattern. `select` all the variables from `health_gen` to the end.
```{r}
nhanes %>%
select(health_gen:smoke_now)
```
We can drop variables using the -var format. Drop the `education` variable.
```{r}
nhanes %>%
select(-education)
```
We can drop a set of variables using the -(var1:var2) format. Drop the variables from `health_gen` to the end.
```{r}
nhanes %>%
select(-(health_gen:smoke_now))
```
# mutate
![](slides/images/mutate.png)
We use `mutate` we make new variables or change existing ones.
Create a **new variable with a specific value**
Create a new variable called `completed_survey` and make all responses to it "Yes".
```{r}
nhanes %>%
mutate(completed_survey = "Yes")
```
Copy your code from above and then add a line where you select only the `completed_survey` variable. Don't forget the pipe (%>%)!
```{r}
nhanes %>%
mutate(completed_survey = "Yes") %>%
select(completed_survey)
```
Create a **new variable based on other variables**
Create a new variable called `pct_days_phys_health_bad` and calculate it as the percentage of self-reported days of bad physical health in the last 30 days. Remember that the `days_phys_hlth_bad` variable is a measure of the **number** of self-reported days of bad physical health in the last 30 days. Then, use `select` to show the `days_phys_hlth_bad` and `pct_days_phys_health_bad` variables.
```{r}
nhanes %>%
mutate(pct_days_phys_health_bad = days_phys_hlth_bad / 30) %>%
select(days_phys_hlth_bad, pct_days_phys_health_bad)
```
Change an **existing variable**
Round the `height` variable to a whole number. Then, use `select` to show only the `height` variable.
```{r}
nhanes %>%
mutate(height = round(height, digits = 0)) %>%
select(height)
```
# filter
![](slides/images/filter.png)
We use `filter` to choose a subset of cases.
Use `filter` to keep only respondents who are divorced. Then, use `select` to show only the `marital_status` variable.
```{r}
nhanes %>%
filter(marital_status == "Divorced") %>%
select(marital_status)
```
Use `filter` to keep only respondents who are **not** divorced. Then, use `select` to show only the `marital_status` variable.
```{r}
nhanes %>%
filter(marital_status != "Divorced") %>%
select(marital_status)
```
Use `filter` to keep only respondents who are divorced or separated. Then, use `select` to show only the `marital_status` variable.
```{r}
nhanes %>%
filter(marital_status == "Divorced" | marital_status == "Separated") %>%
select(marital_status)
```
Use `%in%` within the `filter` function to keep only those who are divorced, separated, or widowed. Then, use `select` to show only the `marital_status` variable.
```{r}
nhanes %>%
filter(marital_status %in% c("Divorced", "Separated", "Widowed")) %>%
select(marital_status)
```
We can chain together multiple `filter` functions. Doing it this way, we don't have create complex logic in one line.
Create a chain that keeps only those are college grads (line #1). Then, `filter` to keep only those who are divorced, separated, or widowed. Finally, use `select` to show only the `education` and `marital_status` variables.
```{r}
nhanes %>%
filter(education == "College Grad") %>%
filter(marital_status %in% c("Divorced", "Separated", "Widowed")) %>%
select(education, marital_status)
```
We can use Use `<`, `>`, `<=`, and `=>` for numeric data.
Use `filter` to only show those reported at least 5 days of physical activity in the last 30 days (this is the `phys_active_days` variable). Then, use `select` to keep only the `phys_active_days` and the `days_phys_hlth_bad` variables.
```{r}
nhanes %>%
filter(phys_active_days >= 5) %>%
select(phys_active_days, days_phys_hlth_bad)
```
We can drop `NAs` with `!is.na`
Do the same thing as above, but drop responses that don't have a response for `days_phys_hlth_bad`. Then, use `select` to keep only the `phys_active_days` and the `days_phys_hlth_bad` variables.
```{r}
nhanes %>%
filter(phys_active_days >= 5) %>%
filter(!is.na(days_phys_hlth_bad)) %>%
select(phys_active_days, days_phys_hlth_bad)
```
You can also drop `NAs` with `drop_na`
Do the same thing as above, but use `drop_na` instead of `!is.na`. Make sure you get the same result!
```{r}
nhanes %>%
filter(phys_active_days >= 5) %>%
drop_na(days_phys_hlth_bad) %>%
select(phys_active_days, days_phys_hlth_bad)
```
# summarize
![](slides/images/summarize.png)
With `summarize`, we can go from a complete dataset down to a summary.
Get the mean hours of sleep per night that respondents say they get.
```{r}
nhanes %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE))
```
We can have multiple arguments in each usage of `summarize`.
In addition to calculating the mean hours of sleep per night, calculate the number of responses.
```{r}
nhanes %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE),
number_of_responses = n())
```
# group_by
![](slides/images/group-by.png)
`summarize` becomes truly powerful when paired with `group_by`, which enables us to perform calculations on each group.
Calculate the mean hours of sleep for females and males using `group_by` and `summarize`.
```{r}
nhanes %>%
group_by(gender) %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE))
```
We can use `group_by` with multiple groups.
Use `group_by` for `gender` and `work` (whether or not respondents are working) before calculating mean hours of sleep.
```{r}
nhanes %>%
group_by(gender, work) %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE),
number_of_observations = n())
```
## count
If we just want to count the number of things per group, we can use `count`.
Use `count` to show the number of responses by highest level of education completed (`education`).
```{r}
nhanes %>%
count(education)
```
We can also count by multiple groups.
Use `count` to show the number of responses for `education` and `phys_active`.
```{r}
nhanes %>%
count(education, phys_active)
```
# arrange
![](slides/images/arrange.png)
With `arrange`, we can reorder rows in a data frame based on the values of one or more variables. R arranges in ascending order by default.
Use `count` to show the number of responses by education level. Then, use `arrange` to order by the number of responses.
```{r}
nhanes %>%
count(education) %>%
arrange(n)
```
We can also arrange in descending order using `desc`.
Do the same thing as above, but put it in descending order using `desc`.
```{r}
nhanes %>%
count(education) %>%
arrange(desc(n))
```
We often use `arrange` at the end of chains to display things in order.
Create a chain that does the following:
1. Uses `filter` to only include those age 30 or older
2. Uses `group_by` to create a male and female group
3. Uses `summarize` to calculate a new variable called `mean_bad_mental_health_days` for males and females
4. Uses `mutate` to round `mean_bad_mental_health_days` to one decimal place
5. Uses `arrange` to put `mean_bad_mental_health_days` in descending order
```{r}
nhanes %>%
filter(age >= 30) %>%
group_by(gender) %>%
summarize(mean_bad_mental_health_days = mean(days_ment_hlth_bad, na.rm = TRUE)) %>%
mutate(mean_bad_mental_health_days = round(mean_bad_mental_health_days, digits = 1)) %>%
arrange(desc(mean_bad_mental_health_days))
```
# Create a new data frame
Sometimes you want to save the results of your work to a new data frame.
Copy the code above and save it to a new data frame called `mental_health_over_30`.
```{r}
mental_health_over_30 <- nhanes %>%
filter(age >= 30) %>%
group_by(gender) %>%
summarize(mean_bad_mental_health_days = mean(days_ment_hlth_bad, na.rm = TRUE)) %>%
mutate(mean_bad_mental_health_days = round(mean_bad_mental_health_days, digits = 1)) %>%
arrange(desc(mean_bad_mental_health_days))
```
# Crosstabs
Sometimes you want your results in a crosstab. We can use the `tabyl` function in `janitor` package to make crosstabs automatically.
Create a crosstab of `gender` and `health_gen`.
```{r}
nhanes %>%
tabyl(gender, health_gen)
```
Add a `drop_na` before your line with `tabyl` to get rid of all NAs.
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen)
```
`janitor` has a set of functions that all start with `adorn_` that add a number of things to our crosstabs. We call them after `tabyl`. For example, `adorn_totals`.
Use the code above and then add totals using `adorn_totals` in the rows and columns.
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen) %>%
adorn_totals(where = c("row", "col"))
```
We can add `adorn_percentages` to add percentages.
Use the code above and then add percentages using `adorn_percentages`.
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen) %>%
adorn_totals(where = c("row", "col")) %>%
adorn_percentages()
```
We can then format these percentages using `adorn_pct_formatting`.
Use the code above and then format the percentages using `adorn_pct_formatting`. Add arguments so that the percentages are rounded to 1 digit. Note that R uses the "half to even" rounding method by default so if you want to round, say, 14.5 to 15 you must use the `rounding` argument (type ?adorn_pct_formatting in the console to learn more).
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen) %>%
adorn_totals(where = c("row", "col")) %>%
adorn_percentages() %>%
adorn_pct_formatting(digits = 1,
rounding = "half up")
```
If we want to include the n alongside percentages, we can use `adorn_ns`.
Use the code above and then add a line with `adorn_ns` to include the n.
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen) %>%
adorn_totals(c("row", "col")) %>%
adorn_percentages() %>%
adorn_pct_formatting(digits = 1,
rounding = "half up") %>%
adorn_ns()
```
We can add titles to our crosstabs using `adorn_title`.
Use the code above and then add a title using `adorn_title`. Use the `placement` argument and see what you get.
```{r}
nhanes %>%
drop_na(gender, health_gen) %>%
tabyl(gender, health_gen) %>%
adorn_totals(c("row", "col")) %>%
adorn_percentages() %>%
adorn_pct_formatting(digits = 0,
rounding = "half up") %>%
adorn_ns() %>%
adorn_title(placement = "combined")
```
We can also do three (or more) way crosstabs automatically by adding more variables to the `tabyl` function.
Use the code above, but add a third variable (`age_decade`) to the line with `drop_na` and the line with `tabyl`. You should get a series of crosstabs.
```{r}
nhanes %>%
drop_na(gender, health_gen, age_decade) %>%
tabyl(gender, health_gen, age_decade) %>%
adorn_totals(c("row", "col")) %>%
adorn_percentages() %>%
adorn_pct_formatting(digits = 0, rounding = "half up") %>%
adorn_ns() %>%
adorn_title()
```