Debian Codegraph @

inst/doc/using_skimr.Rmd

raw
1 ---
2 title: "Using Skimr"
3 date: "`r Sys.Date()`"
4 output: rmarkdown::html_vignette
5 vignette: >
6 %\VignetteIndexEntry{Using Skimr}
7 %\VignetteEngine{knitr::rmarkdown}
8 %\VignetteEncoding{UTF-8}
9 ---
10
11 ## Introduction
12
13 `skimr` is designed to provide summary statistics about variables in data frames,
14 tibbles, data tables and vectors. It is
15 opinionated in its defaults, but easy to modify.
16
17 In base R, the most similar functions are `summary()` for vectors and data
18 frames and `fivenum()` for numeric vectors:
19
20 ```{r}
21 summary(iris)
22 ```
23
24 ```{r}
25 summary(iris$Sepal.Length)
26 ```
27
28 ```{r}
29 fivenum(iris$Sepal.Length)
30 ```
31
32 ```{r}
33 summary(iris$Species)
34 ```
35
36 ## The `skim()` function
37
38 The core function of `skimr` is `skim()`, which is designed to work with
39 (grouped) data frames, and will try coerce other objects to data frames
40 if possible. Like `summary()`, `skim()`'s method for data frames presents
41 results for every column; the statistics it provides depend on the class of
42 the variable.
43
44 ### Skimming data frames
45
46 By design, the main focus of `skimr` is on data frames; it is intended to fit
47 well within a data [pipeline](https://r4ds.had.co.nz/pipes.html) and relies
48 extensively on [tidyverse](https://tidyverse.org/) vocabulary, which
49 focuses on data frames.
50
51 Results of `skim()` are *printed* horizontally, with one section per variable
52 type and one row per variable.
53
54 ```{r, render = knitr::normal_print}
55 library(skimr)
56 skim(iris)
57 ```
58
59 The format of the results are a single wide data frame combining the results,
60 with some additional attributes and two metadata columns:
61
62 - `skim_variable`: name of the original variable
63 - `skim_type`: class of the variable
64
65 Unlike many other objects within `R`, these columns are intrinsic to the
66 `skim_df` class. Dropping these variables will result in a coercion to a
67 `tibble`. The `is_skim_df()` function is used to assert that an object is
68 a skim_df.
69
70 ```{r}
71 skim(iris) |> is_skim_df()
72 ```
73
74 ```{r, render = knitr::normal_print}
75 skim(iris) |>
76 dplyr::select(-skim_type, -skim_variable) |>
77 is_skim_df()
78 ```
79
80 ```{r, render = knitr::normal_print}
81 skim(iris) |>
82 dplyr::select(-n_missing) |>
83 is_skim_df()
84 ```
85
86 In order to avoid type coercion, columns for summary statistics for different
87 types are prefixed with the corresponding `skim_type`. This means that the
88 columns of the `skim_df` are somewhat sparse, with quite a few missing
89 values. This is because for some statistics the representations for different
90 types of variables is different. For example, the mean of a Date variable and
91 of a numeric variable are represented differently when printing, but this
92 cannot be supported in a single vector. The exception to this are
93 `n_missing` and `complete_rate` (missing/number of observations) which are the
94 same for all types of variables.
95
96 ```{r, render = knitr::normal_print}
97 skim(iris) |>
98 tibble::as_tibble()
99 ```
100
101 This is in contrast to `summary.data.frame()`, which stores statistics in a
102 `table`. The distinction is important, because the `skim_df` object is pipeable
103 and easy to use for additional manipulation: for example, the user could select
104 all of the variable means, or all summary statistics for a specific variable.
105
106 ```{r, render = knitr::normal_print}
107 skim(iris) |>
108 dplyr::filter(skim_variable == "Petal.Length")
109 ```
110
111 Most `dplyr` verbs should work as expected.
112
113 ```{r, render = knitr::normal_print}
114 skim(iris) |>
115 dplyr::select(skim_type, skim_variable, n_missing)
116 ```
117
118 The base skimmers `n_missing` and `complete_rate` are computed for all of the
119 columns in the data. But all other type-based skimmers have a namespace. You
120 need to use a `skim_type` prefix to refer to correct column.
121
122 ```{r, render = knitr::normal_print}
123 skim(iris) |>
124 dplyr::select(skim_type, skim_variable, numeric.mean)
125 ```
126
127 `skim()` also supports grouped data created by `dplyr::group_by()`.
128 In this case, one additional column for each grouping variable is added
129 to the `skim_df` object.
130
131 ```{r, render = knitr::normal_print}
132 iris |>
133 dplyr::group_by(Species) |>
134 skim()
135 ```
136
137 Individual columns from a data frame may be selected using tidyverse-style
138 selectors.
139
140 ```{r, render = knitr::normal_print}
141 skim(iris, Sepal.Length, Species)
142 ```
143
144 Or with common `select` helpers.
145
146 ```{r, render = knitr::normal_print}
147 skim(iris, starts_with("Sepal"))
148 ```
149
150 If an individual column is of an unsupported class, it is treated as a
151 character variable with a warning.
152
153 ## Skimming vectors
154
155 In `skimr` v2, `skim()` will attempt to coerce non-data frames (such as vectors
156 and matrices) to data frames. In most cases with vectors, the object being
157 evaluated should be equivalent to wrapping the object in `as.data.frame()`.
158
159 For example, the `lynx` data set is class `ts`.
160
161 ```{r, render = knitr::normal_print}
162 skim(lynx)
163 ```
164
165 Which is the same as coercing to a data frame.
166
167 ```{r}
168 all.equal(skim(lynx), skim(as.data.frame(lynx)))
169 ```
170
171 ## Skimming matrices
172
173 `skimr` does not support skimming matrices directly but coerces them to data
174 frames. Columns in the matrix become variables. This behavior is similar to
175 `summary.matrix()`). Three possible ways to handle matrices with `skim()`
176 parallel the three variations of the mean function for matrices.
177
178 ```{r, render = knitr::normal_print}
179 m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), nrow = 4, ncol = 3)
180 m
181 ```
182
183 Skimming the matrix produces similar results to `colMeans()`.
184
185 ```{r, render = knitr::normal_print}
186 colMeans(m)
187 skim(m) # Similar to summary.matrix and colMeans()
188 ```
189
190 Skimming the transpose of the matrix will give row-wise results.
191
192 ```{r, render = knitr::normal_print}
193 rowMeans(m)
194 skim(t(m))
195 ```
196
197 And call `c()` on the matrix to get results across all columns.
198
199 ```{r, render = knitr::normal_print}
200 skim(c(m))
201 mean(m)
202 ```
203
204 ### Skimming without modification
205
206 `skim_tee()` produces the same printed version as `skim()` but returns the
207 original, unmodified data frame. This allows for continued piping of the
208 original data.
209
210 ```{r, render = knitr::normal_print}
211 iris_setosa <- iris |>
212 skim_tee() |>
213 dplyr::filter(Species == "setosa")
214 head(iris_setosa)
215 ```
216
217 Note, that `skim_tee()` is customized differently than `skim` itself. See below
218 for more details.
219
220 ## Reshaping the results from `skim()`
221
222 As noted above, `skim()` returns a wide data frame. This is usually the most
223 sensible format for the majority of operations when investigating data, but
224 the package has some other functions to help with edge cases.
225
226 First, `partition()` returns a named list of the wide data frames for each data
227 type. Unlike the original data the partitioned data only has columns
228 corresponding to the skimming functions used for this data type. These data
229 frames are, therefore, not `skim_df` objects.
230
231 ```{r, render = knitr::normal_print}
232 iris |>
233 skim() |>
234 partition()
235 ```
236
237 Alternatively, `yank()` selects only the subtable for a specific type. Think of
238 it like `dplyr::select` on column types in the original data. Again, unsuitable
239 columns are dropped.
240
241 ```{r, render = knitr::normal_print}
242 iris |>
243 skim() |>
244 yank("numeric")
245 ```
246
247 `to_long()` returns a single long data frame with columns `variable`, `type`,
248 `statistic` and `formatted`. This is similar but not identical to the `skim_df`
249 object in `skimr` v1.
250
251 ```{r, render = knitr::normal_print}
252 iris |>
253 skim() |>
254 to_long() |>
255 head()
256 ```
257
258 Since the `skim_variable` and `skim_type` columns are a core component of the
259 `skim_df` class, it's possible to get unwanted side effects when using
260 `dplyr::select()`. Instead, use `focus()` to select columns of the skimmed
261 results and keep them as a `skim_df`; it always keeps the metadata column.
262
263 ```{r, render = knitr::normal_print}
264 iris |>
265 skim() |>
266 focus(n_missing, numeric.mean)
267 ```
268
269 ## Rendering the results of `skim()`
270
271 The `skim_df` object is a wide data frame. The display is
272 created by default using `print.skim_df()`; users can specify additional
273 options by explicitly calling `print([skim_df object], ...)`.
274
275 For documents rendered by `knitr`, the package provides a custom `knit_print`
276 method. To use it, the final line of your code chunk should have a `skim_df`
277 object.
278
279 ```{r}
280 skim(Orange)
281 ```
282
283 The same type of rendering is available from reshaped `skim_df` objects, those
284 generated by `partition()` and `yank()` in particular.
285
286 ```{r}
287 skim(Orange) |>
288 yank("numeric")
289 ```
290
291 ## Customizing print options
292
293 Although its not a common use case outside of writing vignettes about `skimr`,
294 you can fall back to default printing methods by adding the chunk option
295 `render = knitr::normal_print`.
296
297 You can also disable the `skimr` summary by setting the chunk option
298 `skimr_include_summary = FALSE`.
299
300 You can change the number of digits shown in the columns of generated statistics
301 by changing the `skimr_digits` chunk option.
302
303 ## Modifying `skim()`
304
305 `skimr` is opinionated in its choice of defaults, but users can easily add,
306 replace, or remove the statistics for a class. For interactive use, you can
307 create your own skimming function with the `skim_with()` factory. `skimr` also
308 has an API for extensions in other packages. Working with that is covered later.
309
310 To add a statistic for a data type, create an `sfl()` (a `skimr` function list)
311 for each class that you want to change:
312
313 ```{r}
314 my_skim <- skim_with(numeric = sfl(new_mad = mad))
315 my_skim(faithful)
316 ```
317
318 As the previous example suggests, the default is to append *new* summary
319 statistics to the preexisting set. This behavior isn't always desirable,
320 especially when you want lots of changes. To stop appending, set
321 `append = FALSE`.
322
323 ```{r}
324 my_skim <- skim_with(numeric = sfl(new_mad = mad), append = FALSE)
325 my_skim(faithful)
326 ```
327
328 You can also use `skim_with()` to remove specific statistics by setting them to
329 `NULL`. This is commonly used to disable the inline histograms and spark graphs.
330
331 ```{r}
332 no_hist <- skim_with(ts = sfl(line_graph = NULL))
333 no_hist(Nile)
334 ```
335
336 The same pattern applies to changing skimmers for multiple classes
337 simultaneously. If you want to partially-apply function arguments, use the
338 Tidyverse lambda syntax.
339
340 ```{r}
341 my_skim <- skim_with(
342 numeric = sfl(total = ~ sum(., na.rm = TRUE)),
343 factor = sfl(missing = ~ sum(is.na(.))),
344 append = FALSE
345 )
346
347 my_skim(iris)
348 ```
349
350 To modify the "base" skimmers, refer to them in a similar manner. Since base
351 skimmers are usually a small group, they must return the same type for all
352 data types in R, `append` doesn't apply here.
353
354 ```{r}
355 my_skim <- skim_with(base = sfl(length = length))
356 my_skim(faithful)
357 ```
358
359 ## Extending `skimr`
360
361 Packages may wish to export their own `skim()` functions. Use `skim_with()` for
362 this. In fact, this is how `skimr` generates its version of `skim()`.
363
364 ```{r}
365 #' @export
366 my_package_skim <- skim_with()
367 ```
368
369 Alternatively, defaults for another data types can be added to `skimr` with the
370 `get_skimmers` generic. The method for your data type should return an `sfl()`.
371 Unlike the `sfl()` used interactively, you also need to set the `skim_type`
372 argument. It should match the method type in the function signature.
373
374 ```{r}
375 get_skimmers.my_type <- function(column) {
376 sfl(
377 skim_type = "my_type",
378 total = sum
379 )
380 }
381
382 my_data <- data.frame(
383 my_type = structure(1:3, class = c("my_type", "integer"))
384 )
385 skim(my_data)
386 ```
387
388 An extended example is available in the vignette *Supporting additional
389 objects*.
390
391 ## Solutions to common rendering problems
392
393 The details of rendering are dependent on the operating system R is running on,
394 the locale of the installation, and the fonts installed. Rendering may also
395 differ based on whether it occurs in the console or when knitting to specific
396 types of documents such as HTML and PDF.
397
398 The most commonly reported problems involve rendering the spark graphs (inline
399 histogram and line chart) on Windows. One common fix is to switch your locale. The
400 function `fix_windows_histograms()` does this for you.
401
402 In order to render the sparkgraphs in html or PDF histogram you may need to
403 change fonts to one that supports blocks or Braille (depending on which you
404 need). Please review the separate vignette and associated template for details.