Debian Codegraph @

inst/doc/broom_and_dplyr.Rmd

raw
1 ---
2 title: "broom and dplyr"
3 date: "`r Sys.Date()`"
4 output: rmarkdown::html_vignette
5 vignette: >
6 %\VignetteIndexEntry{broom and dplyr}
7 %\VignetteEngine{knitr::rmarkdown}
8 %\VignetteEncoding{UTF-8}
9 ---
10
11 ```{r}
12 #| label: setup
13 #| include: false
14 knitr::opts_chunk$set(message = FALSE, warning = FALSE)
15
16 if (rlang::is_installed("ggplot2")) {
17 run <- TRUE
18 } else {
19 run <- FALSE
20 }
21
22 knitr::opts_chunk$set(
23 eval = run
24 )
25 ```
26
27 # broom and dplyr
28
29 While broom is useful for summarizing the result of a single analysis in a consistent format, it is really designed for high-throughput applications, where you must combine results from multiple analyses. These could be subgroups of data, analyses using different models, bootstrap replicates, permutations, and so on. In particular, it plays well with the `nest/unnest` functions in `tidyr` and the `map` function in `purrr`. First, loading necessary packages and setting some defaults:
30
31 ```{r}
32 library(broom)
33 library(tibble)
34 library(ggplot2)
35 library(dplyr)
36 library(tidyr)
37 library(purrr)
38
39 theme_set(theme_minimal())
40 ```
41
42 Let's try this on a simple dataset, the built-in `Orange`. We start by coercing `Orange` to a `tibble`. This gives a nicer print method that will especially useful later on when we start working with list-columns.
43
44 ```{r}
45 data(Orange)
46
47 Orange <- as_tibble(Orange)
48 Orange
49 ```
50
51 This contains 35 observations of three variables: `Tree`, `age`, and `circumference`. `Tree` is a factor with five levels describing five trees. As might be expected, age and circumference are correlated:
52
53 ```{r}
54 cor(Orange$age, Orange$circumference)
55
56 ggplot(Orange, aes(age, circumference, color = Tree)) +
57 geom_line()
58 ```
59
60 Suppose you want to test for correlations individually *within* each tree. You can do this with dplyr's `group_by`:
61
62 ```{r}
63 #| message: false
64 #| warning: false
65 Orange |>
66 group_by(Tree) |>
67 summarize(correlation = cor(age, circumference))
68 ```
69
70 (Note that the correlations are much higher than the aggregated one, and furthermore we can now see it is similar across trees).
71
72 Suppose that instead of simply estimating a correlation, we want to perform a hypothesis test with `cor.test`:
73
74 ```{r}
75 ct <- cor.test(Orange$age, Orange$circumference)
76 ct
77 ```
78
79 This contains multiple values we could want in our output. Some are vectors of length 1, such as the p-value and the estimate, and some are longer, such as the confidence interval. We can get this into a nicely organized tibble using the `tidy` function:
80
81 ```{r}
82 tidy(ct)
83 ```
84
85 Often, we want to perform multiple tests or fit multiple models, each on a different part of the data. In this case, we recommend a `nest-map-unnest` workflow. For example, suppose we want to perform correlation tests for each different tree. We start by `nest`ing our data based on the group of interest:
86
87 ```{r}
88 nested <- Orange |>
89 nest(data = -Tree)
90 ```
91
92 Then we run a correlation test for each nested tibble using `purrr::map`:
93
94 ```{r}
95 nested |>
96 mutate(test = map(data, ~ cor.test(.x$age, .x$circumference)))
97 ```
98
99 This results in a list-column of S3 objects. We want to tidy each of the objects, which we can also do with `map`.
100
101 ```{r}
102 nested |>
103 mutate(
104 test = map(data, ~ cor.test(.x$age, .x$circumference)), # S3 list-col
105 tidied = map(test, tidy)
106 )
107 ```
108
109 Finally, we want to unnest the tidied data frames so we can see the results in a flat tibble. All together, this looks like:
110
111 ```{r}
112 Orange |>
113 nest(data = -Tree) |>
114 mutate(
115 test = map(data, ~ cor.test(.x$age, .x$circumference)), # S3 list-col
116 tidied = map(test, tidy)
117 ) |>
118 unnest(tidied)
119 ```
120
121 This workflow becomes even more useful when applied to regressions. Untidy output for a regression looks like:
122
123 ```{r}
124 lm_fit <- lm(age ~ circumference, data = Orange)
125 summary(lm_fit)
126 ```
127
128 where we tidy these results, we get multiple rows of output for each model:
129
130 ```{r}
131 tidy(lm_fit)
132 ```
133
134 Now we can handle multiple regressions at once using exactly the same workflow as before:
135
136 ```{r}
137 Orange |>
138 nest(data = -Tree) |>
139 mutate(
140 fit = map(data, ~ lm(age ~ circumference, data = .x)),
141 tidied = map(fit, tidy)
142 ) |>
143 unnest(tidied)
144 ```
145
146 You can just as easily use multiple predictors in the regressions, as shown here on the `mtcars` dataset. We nest the data into automatic and manual cars (the `am` column), then perform the regression within each nested tibble.
147
148 ```{r}
149 data(mtcars)
150 mtcars <- as_tibble(mtcars) # to play nicely with list-cols
151 mtcars
152
153 mtcars |>
154 nest(data = -am) |>
155 mutate(
156 fit = map(data, ~ lm(wt ~ mpg + qsec + gear, data = .x)), # S3 list-col
157 tidied = map(fit, tidy)
158 ) |>
159 unnest(tidied)
160 ```
161
162 What if you want not just the `tidy` output, but the `augment` and `glance` outputs as well, while still performing each regression only once? Since we're using list-columns, we can just fit the model once and use multiple list-columns to store the tidied, glanced and augmented outputs.
163
164 ```{r}
165 regressions <- mtcars |>
166 nest(data = -am) |>
167 mutate(
168 fit = map(data, ~ lm(wt ~ mpg + qsec + gear, data = .x)),
169 tidied = map(fit, tidy),
170 glanced = map(fit, glance),
171 augmented = map(fit, augment)
172 )
173
174 regressions |>
175 unnest(tidied)
176
177 regressions |>
178 unnest(glanced)
179
180 regressions |>
181 unnest(augmented)
182 ```
183
184 By combining the estimates and p-values across all groups into the same tidy data frame (instead of a list of output model objects), a new class of analyses and visualizations becomes straightforward. This includes
185
186 - Sorting by p-value or estimate to find the most significant terms across all tests
187 - P-value histograms
188 - Volcano plots comparing p-values to effect size estimates
189
190 In each of these cases, we can easily filter, facet, or distinguish based on the `term` column. In short, this makes the tools of tidy data analysis available for the *results* of data analysis and models, not just the inputs.