Debian Codegraph @

R/stats.R

raw
1 #' Summary statistic functions
2 #'
3 #' `skimr` provides extensions to a variety of functions with R's stats package
4 #' to simplify creating summaries of data. All functions are vectorized over the
5 #' first argument. Additional arguments should be set in the [sfl()] that sets
6 #' the appropriate skimmers for a data type. You can use these, along with other
7 #' vectorized R functions, for creating custom sets of summary functions for
8 #' a given data type.
9 #'
10 #' @seealso [get_skimmers()] for customizing the functions called by [skim()].
11 #' @param x A vector
12 #' @param n_bins In `inline_hist`, the number of histogram bars.
13 #' @param length.out In `inline_linegraph`, the length of the character time
14 #' series.
15 #' @param max_char In `top` = 3, max_levels = 4
16 #' @name stats
17 NULL
18
19 #' @describeIn stats Calculate the sum of `NA` and `NULL` (i.e. missing) values.
20 #' @export
21 n_missing <- function(x) {
22 sum(is.na(x) | is.null(x))
23 }
24
25 #' @describeIn stats Calculate the sum of not `NA` and `NULL` (i.e. missing)
26 #' values.
27 #' @export
28 n_complete <- function(x) {
29 sum(!is.na(x) & !is.null(x))
30 }
31
32 #' @describeIn stats Calculate complete values; complete values are not missing.
33 #' @export
34 complete_rate <- function(x) {
35 1 - n_missing(x) / length(x)
36 }
37
38 #' @describeIn stats Calculate the number of rows containing only whitespace
39 #' values using s+ regex.
40 #' @export
41 n_whitespace <- function(x) {
42 whitespace <- grepl("^\\s+$", x)
43 sum(whitespace)
44 }
45
46 #' @describeIn stats Create a contingency table and arrange its levels in
47 #' descending order. In case of ties, the ordering of results is alphabetical
48 #' and depends upon the locale. `NA` is treated as a ordinary value for
49 #' sorting.
50 #' @export
51 sorted_count <- function(x) {
52 tab <- table(x, useNA = "no")
53 names_tab <- names(tab)
54 if (is.element("", names_tab)) {
55 names_tab[names_tab == ""] <- "empty"
56 warning(
57 "Variable contains value(s) of \"\" that have been ",
58 "converted to \"empty\"."
59 )
60 }
61 out <- rlang::set_names(as.integer(tab), names_tab)
62 sort(out, decreasing = TRUE)
63 }
64
65 #' @describeIn stats Compute and collapse a contingency table into a single
66 #' character scalar. Wraps [sorted_count()].
67 #' @param max_levels The maximum number of levels to be displayed.
68 #' @export
69 top_counts <- function(x, max_char = 3, max_levels = 4) {
70 counts <- sorted_count(x)
71 if (length(counts) > max_levels) {
72 top <- counts[seq_len(max_levels)]
73 } else {
74 top <- counts
75 }
76 top_names <- substr(names(top), 1, max_char)
77 paste0(top_names, ": ", top, collapse = ", ")
78 }
79
80 #' @describeIn stats Generate inline histogram for numeric variables. The
81 #' character length of the histogram is controlled by the formatting options
82 #' for character vectors.
83 #' @export
84 inline_hist <- function(x, n_bins = 8) {
85 # For the purposes of the histogram, treat infinite as NA
86 # (before the test for all NA)
87 if (any(is.infinite(x))) {
88 x[is.infinite(x)] <- NA
89 warning(
90 "Variable contains Inf or -Inf value(s) that were converted to NA."
91 )
92 }
93
94 # Handle empty and NA vectors (is.na is TRUE for NaN)
95 if (length(x) < 1 || all(is.na(x))) {
96 return(" ")
97 }
98
99 # Addresses a known bug in cut()
100 if (all(x == 0, na.rm = TRUE)) x <- x + 1
101 hist_dt <- table(cut(x, n_bins))
102 hist_dt <- hist_dt / max(hist_dt)
103 spark_bar(hist_dt)
104 }
105
106 #' Draw a sparkline bar graph with unicode block characters
107 #'
108 #' Rendered using
109 #' [block elements](https://en.wikipedia.org/wiki/Block_Elements).
110 #' In most common fixed width fonts these are rendered wider than regular
111 #' characters which means they are not suitable if you need precise alignment.
112 #' Based on the function in the pillar package.
113 #'
114 #' @param x A numeric vector between 0 and 1
115 #' @param safe Nominally there are 8 block elements from 1/8 height to full
116 #' height (8/8). However, the half-height and full-height blocks appear
117 #' to be rendered inconsistently (possibly due to font substitution).
118 #' @examples
119 #' \dontrun{
120 #' x <- seq(0, 1, length = 6)
121 #' spark_bar(x)
122 #' spark_bar(sample(x))
123 #'
124 #' # This might work if you're lucky
125 #' spark_bar(seq(0, 1, length = 8), safe = FALSE)
126 #'
127 #' spark_bar(c(0, NA, 0.5, NA, 1))
128 #' }
129 #' @noRd
130 spark_bar <- function(x, safe = TRUE) {
131 stopifnot(is.numeric(x))
132
133 bars <- vapply(0x2581:0x2588, intToUtf8, character(1))
134 if (safe) {
135 bars <- bars[-c(4, 8)]
136 }
137
138 factor <- cut(
139 x,
140 breaks = seq(0, 1, length.out = length(bars) + 1),
141 labels = bars,
142 include.lowest = TRUE
143 )
144 chars <- as.character(factor)
145 chars[is.na(chars)] <- bars[length(bars)]
146 paste0(chars, collapse = "")
147 }
148
149 #' @describeIn stats Calculate the number of blank values in a character vector.
150 #' A "blank" is equal to "".
151 #' @export
152 n_empty <- function(x) {
153 empty_strings <- c("")
154 sum(x %in% empty_strings)
155 }
156
157 #' @describeIn stats Calculate the minimum number of characters within a
158 #' character vector.
159 #' @export
160 min_char <- function(x) {
161 if (all(is.na(x))) {
162 return(NA)
163 }
164 characters <- nchar(x, allowNA = TRUE)
165 min(characters, na.rm = TRUE)
166 }
167
168 #' @describeIn stats Calculate the maximum number of characters within a
169 #' character vector.
170 #' @export
171 max_char <- function(x) {
172 if (all(is.na(x))) {
173 return(NA)
174 }
175 characters <- nchar(x, allowNA = TRUE)
176 max(characters, na.rm = TRUE)
177 }
178
179 #' @describeIn stats Calculate the number of unique elements but remove `NA`.
180 #' @export
181 n_unique <- function(x) {
182 un <- x[!is.na(x)]
183 un <- unique(un)
184 length(un)
185 }
186
187 #' @describeIn stats Get the start for a time series without the frequency.
188 #' @export
189 ts_start <- function(x) {
190 stats::start(x)[1]
191 }
192
193 #' @describeIn stats Get the finish for a time series without the frequency.
194 #' @export
195 ts_end <- function(x) {
196 stats::end(x)[1]
197 }
198
199 #' @describeIn stats Generate inline line graph for time series variables. The
200 #' character length of the line graph is controlled by the formatting options
201 #' for character vectors.
202 #' Based on the function in the pillar package.
203 #' @export
204 inline_linegraph <- function(x, length.out = 16) {
205 t <- x[!is.na(x)]
206 id <- seq(1, length(t), length.out = length.out)
207 normalized <- normalize01(t[floor(id)])
208 spark_line(normalized)
209 }
210
211 # Rescale data to be between 0 and 1
212 normalize01 <- function(x) {
213 (x - min(x)) / (max(x) - min(x))
214 }
215
216 #' Draw a sparkline line graph with Braille characters.
217 #'
218 #' @inheritParams spark_bar
219 #' @examples
220 #' \dontrun{
221 #' x <- seq(0, 1, length = 10)
222 #' spark_line(x)
223 #' }
224 #' @noRd
225 spark_line <- function(x) {
226 stopifnot(is.numeric(x))
227
228 y <- findInterval(x, seq(0, 1, length.out = 5), all.inside = TRUE)
229
230 ind <- matrix(y, ncol = 2, byrow = TRUE)
231 ind[, 2] <- ind[, 2] + 4
232
233 chars <- apply(ind, 1, braille)
234 paste0(chars, collapse = "")
235 }
236
237 # https://en.wikipedia.org/wiki/Braille_Patterns
238 braille <- function(x) {
239 # remap to braille sequence
240 x <- c(7L, 3L, 2L, 1L, 8L, 6L, 5L, 4L)[x]
241
242 raised <- 1:8 %in% x
243
244 # offset in hex is 2800
245 val <- 10240 + sum(raised * 2^(0:7))
246
247 intToUtf8(val)
248 }
249
250 #' @describeIn stats Get the length of the shortest list in a vector of lists.
251 #' @export
252 list_lengths_min <- function(x) {
253 x <- x[!is.na(x)]
254 l <- lengths(x)
255 if (length(l) > 0) {
256 min(l)
257 } else {
258 NA
259 }
260 }
261
262 #' @describeIn stats Get the median length of the lists.
263 #' @export
264 list_lengths_median <- function(x) {
265 x <- x[!is.na(x)]
266 l <- lengths(x)
267 if (length(l) > 0) {
268 stats::median(l)
269 } else {
270 NA
271 }
272 }
273
274 #' @describeIn stats Get the maximum length of the lists.
275 #' @export
276 list_lengths_max <- function(x) {
277 x <- x[!is.na(x)]
278 l <- lengths(x)
279 if (length(l) > 0) {
280 max(l)
281 } else {
282 NA
283 }
284 }
285
286 #' @describeIn stats Get the length of the shortest list in a vector of lists.
287 #' @export
288 list_min_length <- function(x) {
289 l <- lengths(x)
290 min(l)
291 }
292
293 #' @describeIn stats Get the length of the longest list in a vector of lists.
294 #' @export
295 list_max_length <- function(x) {
296 l <- lengths(x)
297 max(l)
298 }
299
300 #' @describeIn stats Calculate the minimum within a
301 #' Date vector.
302 #' @export
303 min_date <- function(x) {
304 if (all(is.na(x))) {
305 return(NA)
306 }
307 min(x, na.rm = TRUE)
308 }
309
310 #' @describeIn stats Calculate the maximum of
311 #' Date vector.
312 #' @export
313 max_date <- function(x) {
314 if (all(is.na(x))) {
315 return(NA)
316 }
317 max(x, na.rm = TRUE)
318 }