Debian Codegraph @

R/reshape.R

raw
1 #' Separate a big `skim_df` into smaller data frames, by type.
2 #'
3 #' The data frames produced by [skim()] are wide and sparse, filled with
4 #' columns that are mostly `NA`. For that reason, it can be convenient to
5 #' work with "by type" subsets of the original data frame. These smaller
6 #' subsets have their `NA` columns removed.
7 #'
8 #' `partition()` creates a list of smaller `skim_df` data frames. Each entry
9 #' in the list is a data type from the original `skim_df`. The inverse of
10 #' `partition()` is `bind()`, which takes the list and produces the original
11 #' `skim_df`. While `partition()` keeps all of the subtables as list entries,
12 #' `yank()` gives you a single subtable for a data type.
13 #'
14 #' @param data A `skim_df`.
15 #' @param skim_type A character scalar. The subtable to extract from a
16 #' `skim_df`.
17 #' @return A `skim_list` of `skim_df`'s, by type.
18 #' @examples
19 #' # Create a wide skimmed data frame (a skim_df)
20 #' skimmed <- skim(iris)
21 #'
22 #' # Separate into a list of subtables by type
23 #' separate <- partition(skimmed)
24 #'
25 #' # Put back together
26 #' identical(bind(separate), skimmed)
27 #' # > TRUE
28 #'
29 #' # Alternatively, get the subtable of a particular type
30 #' yank(skimmed, "factor")
31 #' @export
32 partition <- function(data) {
33 assert_is_skim_df(data)
34 data_as_list <- split(data, data$skim_type)
35 groups <- group_names(data)
36 base <- base_skimmers(data)
37
38 skimmers <- reconcile_skimmers(data, groups, base)
39
40 # Check to see that there are at least one, known used skim function
41 # within the data. This can be reduced after using focus(). This indexing
42 # is used so that the lookup order matches that of `data_as_list`.
43 has_skim_data <- lengths(skimmers)[names(data_as_list)] > 0
44 elements_to_keep <- has_skim_data | any(base %in% names(data))
45 reduced <- purrr::imap(
46 data_as_list[elements_to_keep],
47 simplify_skimdf,
48 skimmers = skimmers,
49 groups = groups,
50 base = base
51 )
52
53 reassign_skim_attrs(
54 reduced,
55 data,
56 class = c("skim_list", "list"),
57 skimmers_used = skimmers
58 )
59 }
60
61 #' Align the skimmers_used attribute with the current columns in the data
62 #'
63 #' This catches the case where users partition (or more likely print) a data
64 #' frame that has had columns added after skimming.
65 #' @noRd
66 reconcile_skimmers <- function(data, groups, base) {
67 all_columns <- colnames(data)
68 skimmers_used <- skimmers_used(data)
69 if (length(skimmers_used) == 0) {
70 return(skimmers_used)
71 }
72 skimmers_from_names <- skimmers_from_names(all_columns, skimmers_used)
73 with_base_columns <- c(
74 "skim_variable",
75 "skim_type",
76 groups,
77 base,
78 collapse_skimmers(skimmers_used)
79 )
80 matched_cols <- dplyr::intersect(all_columns, with_base_columns)
81 extra_cols <- dplyr::setdiff(all_columns, with_base_columns)
82 if (length(extra_cols) > 0) {
83 grouped <- dplyr::group_by(data, .data$skim_type)
84 complete_by_type <- dplyr::summarise(
85 grouped,
86 dplyr::across(tidyselect::all_of(extra_cols), ~ !all(is.na(.x)))
87 )
88 complete_cols <- purrr::pmap(
89 complete_by_type,
90 get_complete_columns,
91 names = extra_cols
92 )
93 new_cols_by_type <- rlang::set_names(
94 complete_cols,
95 complete_by_type$skim_type
96 )
97 skimmers_from_names <- purrr::list_merge(
98 skimmers_from_names,
99 !!!new_cols_by_type
100 )
101 }
102
103 skimmers_from_names
104 }
105
106 skimmers_from_names <- function(names, skimmers) {
107 matched <- purrr::imap(skimmers, match_skimmers, names)
108 purrr::set_names(matched, names(skimmers))
109 }
110
111 match_skimmers <- function(fun_names, type, values_to_match) {
112 stripped_values <- stringr::str_remove(
113 values_to_match,
114 paste0("^", type, "\\.")
115 )
116 dplyr::intersect(stripped_values, fun_names)
117 }
118
119 collapse_skimmers <- function(skimmers_used) {
120 with_type <- purrr::imap(skimmers_used, ~ paste(.y, .x, sep = "."))
121 purrr::flatten_chr(with_type)
122 }
123
124 get_complete_columns <- function(skim_type, ..., names) {
125 names[c(...)]
126 }
127
128 #' For each type subtable, only select columns generated by this type's skimmers
129 #' This function also catches the case where the user removed columns from
130 #' the skim_df
131 #' @noRd
132 simplify_skimdf <- function(data, skim_type, skimmers, groups, base) {
133 stopifnot(has_variable_column(data))
134 names(data) <- stringr::str_remove(names(data), paste0(skim_type, "\\."))
135 keep <- c("skim_variable", groups, base, skimmers[[skim_type]])
136 out <- dplyr::select(data, tidyselect::any_of(keep))
137
138 structure(
139 out,
140 class = c("one_skim_df", "tbl_df", "tbl", "data.frame"),
141 skim_type = skim_type
142 )
143 }
144
145 #' @describeIn partition The inverse of a `partition()`. Rebuild the original
146 #' `skim_df`.
147 #' @export
148 bind <- function(data) {
149 assert_is_skim_list(data)
150 with_namespaces <- purrr::imap(data, add_namespaces)
151 combined <- dplyr::bind_rows(!!!with_namespaces, .id = "skim_type")
152 reassign_skim_attrs(combined, data)
153 }
154
155 add_namespaces <- function(data, skim_type) {
156 base <- base_skimmers(data)
157 meta_columns <- c("skim_variable", dplyr::group_vars(data), base)
158 no_meta_columns <- dplyr::setdiff(names(data), meta_columns)
159 with_namespace <- paste(skim_type, no_meta_columns, sep = ".")
160
161 # TODO(michaelquinn32): Drop this when vctrs interface works correctly.
162 names(data) <- c(meta_columns, with_namespace)
163 attr(data, "skim_type") <- NULL
164 tibble::as_tibble(data)
165 }
166
167 #' @describeIn partition Extract a subtable from a `skim_df` with a particular
168 #' type.
169 #' @export
170 yank <- function(data, skim_type) {
171 partition(data)[[skim_type]]
172 }
173
174 #' Only show a subset of summary statistics after skimming
175 #'
176 #' This function is a variant of [dplyr::select()] designed to work with
177 #' `skim_df` objects. When using `focus()`, `skimr` metadata columns are kept,
178 #' and `skimr` print methods are still utilized. Otherwise, the signature and
179 #' behavior is identical to [dplyr::select()].
180 #'
181 #' @param .data A `skim_df` object.
182 #' @param ... One or more unquoted expressions separated by commas. Variable
183 #' names can be used as if they were positions in the data frame, so
184 #' expressions like x:y can be used to select a range of variables.
185 #' @examples
186 #' # Compare
187 #' iris |>
188 #' skim() |>
189 #' dplyr::select(n_missing)
190 #'
191 #' iris |>
192 #' skim() |>
193 #' focus(n_missing)
194 #'
195 #' # This is equivalent to
196 #' iris |>
197 #' skim() |>
198 #' dplyr::select(skim_variable, skim_type, n_missing)
199 #' @export
200 focus <- function(.data, ...) {
201 assert_is_skim_df(.data)
202 reduced <- dplyr::select(.data, "skim_type", "skim_variable", ...)
203 if (could_be_skim_df(reduced)) {
204 skimmers <- reconcile_skimmers(
205 reduced,
206 group_names(.data),
207 base_skimmers(.data)
208 )
209 reassign_skim_attrs(reduced, .data, skimmers_used = skimmers)
210 } else {
211 stop("Cannot drop 'skim_variable' or 'skim_type' columns")
212 }
213 }
214
215 #' Create "long" skim output
216 #'
217 #' Skim results returned as a tidy long data frame with four columns:
218 #' variable, type, stat and formatted.
219 #'
220 #' @param .data A data frame or an object that can be coerced into a data frame.
221 #' @param ... Columns to select for skimming. When none are provided, the
222 #' default is to skim all columns.
223 #' @param skim_fun The skim function used.
224 #' @return A tibble
225 #' @examples
226 #' to_long(iris)
227 #' to_long(skim(iris))
228 #' @export
229 to_long <- function(.data, ..., skim_fun = skim) {
230 UseMethod("to_long")
231 }
232
233 #' @describeIn to_long Skim a data frame and convert the results to a
234 #' long data frame.
235 #' @export
236 to_long.default <- function(.data, ..., skim_fun = skim) {
237 skimmed <- skim_fun(.data, ...)
238 to_long(skimmed, ..., skim_fun)
239 }
240
241 #' @describeIn to_long Transform a skim_df to a long data frame.
242 #' @export
243 to_long.skim_df <- function(.data, ..., skim_fun = skim) {
244 .data <- dplyr::mutate(.data, dplyr::across(dplyr::everything(), as.character))
245 tidyr::pivot_longer(
246 .data,
247 cols = c(-"skim_type", -"skim_variable"),
248 names_to = "stat",
249 values_to = "formatted",
250 values_drop_na = TRUE
251 )
252 }