Debian Codegraph @

R/deprecated-0-7-0.R

raw
1 # This script contains all functions and methods that will be deprecated
2 # in 0.7.0 and removed in the next release.
3
4 # data.frame tidiers -------------------------------------------------------
5 # this one breaks some other functionality that new functions rely
6 # re: infinite recursion. Don't hard-deprecate, but trigger error.
7
8 #' Tidiers for data.frame objects
9 #'
10 #' Data frame tidiers are deprecated and will be removed from an upcoming
11 #' release of broom.
12 #'
13 #' These perform tidy summaries of data.frame objects. \code{tidy} produces
14 #' summary statistics about each column, while \code{glance} simply reports
15 #' the number of rows and columns. Note that \code{augment.data.frame} will
16 #' throw an error.
17 #'
18 #' @param x A data.frame
19 #' @param data data, not used
20 #' @param na.rm a logical value indicating whether \code{NA} values should
21 #' be stripped before the computation proceeds.
22 #' @param trim the fraction (0 to 0.5) of observations to be trimmed from
23 #' each end of \code{x} before the mean is computed. Passed to the
24 #' \code{trim} argument of \code{\link{mean}}
25 #' @param ... Additional arguments for other methods.
26 #'
27 #' @author David Robinson, Benjamin Nutter
28 #'
29 #' @source
30 #' Skew and Kurtosis functions are adapted from implementations in the \code{moments} package: \cr
31 #' Lukasz Komsta and Frederick Novomestky (2015). moments: Moments, cumulants, skewness,
32 #' kurtosis and related tests. R package version 0.14. \cr
33 #' https://CRAN.R-project.org/package=moments
34 #'
35 #' @examplesIf rlang::is_installed("ggplot2")
36 #'
37 #' td <- tidy(mtcars)
38 #' td
39 #'
40 #' glance(mtcars)
41 #'
42 #' library(ggplot2)
43 #' # compare mean and standard deviation
44 #' ggplot(td, aes(mean, sd)) + geom_point() +
45 #' geom_text(aes(label = column), hjust = 1, vjust = 1) +
46 #' scale_x_log10() + scale_y_log10() + geom_abline()
47 #'
48 #' @name data.frame_tidiers
49
50 #' @rdname data.frame_tidiers
51 #'
52 #' @return \code{tidy.data.frame} produces a data frame with one
53 #' row per original column, containing summary statistics of each:
54 #' \item{column}{name of original column}
55 #' \item{n}{Number of valid (non-NA) values}
56 #' \item{mean}{mean}
57 #' \item{sd}{standard deviation}
58 #' \item{median}{median}
59 #' \item{trimmed}{trimmed mean, with trim defaulting to .1}
60 #' \item{mad}{median absolute deviation (from the median)}
61 #' \item{min}{minimum value}
62 #' \item{max}{maximum value}
63 #' \item{range}{range}
64 #' \item{skew}{skew}
65 #' \item{kurtosis}{kurtosis}
66 #' \item{se}{standard error}
67 #'
68 #' @export
69 #' @family deprecated
70 tidy.data.frame <- function(x, ..., na.rm = TRUE, trim = 0.1) {
71 .Deprecated(
72 msg = "Data frame tidiers are deprecated and will be removed in an upcoming release of broom."
73 )
74 ret <-
75 tibble::tibble(
76 column = names(x),
77 n = vapply(
78 X = x,
79 FUN = function(k) sum(!is.na(k)),
80 FUN.VALUE = numeric(1)
81 ),
82 mean = vapply(
83 X = x,
84 FUN = mean,
85 FUN.VALUE = numeric(1),
86 na.rm = na.rm
87 ),
88 sd = vapply(
89 X = x,
90 FUN = stats::sd,
91 FUN.VALUE = numeric(1),
92 na.rm = na.rm
93 ),
94 median = vapply(
95 X = x,
96 FUN = stats::median,
97 FUN.VALUE = numeric(1),
98 na.rm = na.rm
99 ),
100 trimmed = vapply(
101 X = x,
102 FUN = mean,
103 FUN.VALUE = numeric(1),
104 na.rm = na.rm,
105 trim = trim
106 ),
107 mad = vapply(
108 X = x,
109 FUN = median_abs_dev,
110 FUN.VALUE = numeric(1),
111 na.rm = na.rm
112 ),
113 min = vapply(
114 X = x,
115 FUN = min,
116 FUN.VALUE = numeric(1),
117 na.rm = na.rm
118 ),
119 max = vapply(
120 X = x,
121 FUN = max,
122 FUN.VALUE = numeric(1),
123 na.rm = na.rm
124 ),
125 range = vapply(
126 X = x,
127 FUN = function(k, na.rm) diff(range(k, na.rm = na.rm)),
128 FUN.VALUE = numeric(1),
129 na.rm = na.rm
130 ),
131 skew = vapply(
132 X = x,
133 FUN = skewness,
134 FUN.VALUE = numeric(1),
135 na.rm = na.rm
136 ),
137 kurtosis = vapply(
138 X = x,
139 FUN = kurtosis,
140 FUN.VALUE = numeric(1),
141 na.rm = na.rm
142 )
143 )
144
145 ret$se <- ret$sd / sqrt(ret$n)
146
147 ret
148 }
149
150
151 #' @rdname data.frame_tidiers
152 #'
153 #' @export
154 #' @family deprecated
155 augment.data.frame <- function(x, data, ...) {
156 cli::cli_abort(
157 "{.arg x} should be a model, not a {.cls data.frame}."
158 )
159 }
160
161
162 #' @rdname data.frame_tidiers
163 #'
164 #' @return \code{glance} returns a one-row data.frame with
165 #' \item{nrow}{number of rows}
166 #' \item{ncol}{number of columns}
167 #' \item{complete.obs}{number of rows that have no missing values}
168 #' \item{na.fraction}{fraction of values across all rows and columns that
169 #' are missing}
170 #'
171 #' @export
172 #' @family deprecated
173 glance.data.frame <- function(x, ...) {
174 .Deprecated(
175 msg = "Data frame tidiers are deprecated and will be removed in an upcoming release of broom."
176 )
177 ret <- tibble::tibble(
178 nrow = nrow(x),
179 ncol = ncol(x)
180 )
181 ret$complete.obs <- sum(stats::complete.cases(x))
182 ret$na.fraction <- mean(is.na(x))
183 return(ret)
184 }
185
186
187 # Basic code inspired by moments::skew
188 skewness <- function(x, na.rm = FALSE) {
189 n <- sum(!is.na(x))
190 (sum((x - mean(x, na.rm = na.rm))^3) / n) /
191 (sum((x - mean(x, na.rm = na.rm))^2) / n)^(3 / 2)
192 }
193
194 # Basic code inspired by moments::kurtosis
195 kurtosis <- function(x, na.rm = FALSE) {
196 n <- sum(!is.na(x))
197 n *
198 sum((x - mean(x, na.rm = na.rm))^4) /
199 (sum((x - mean(x, na.rm = na.rm))^2)^2)
200 }
201
202 median_abs_dev <- function(x, na.rm = FALSE) {
203 stats::median(abs(x - stats::median(x, na.rm = na.rm)), na.rm = na.rm)
204 }
205
206 # bootstrap --------------------------------------------------------------
207
208 #' Set up bootstrap replicates of a dplyr operation
209 #'
210 #' The \code{bootstrap()} function is deprecated and will be removed from
211 #' an upcoming release of broom. For tidy resampling, please use the rsample
212 #' package instead. Functionality is no longer supported for this method.
213 #'
214 #' @param df a data frame
215 #' @param m number of bootstrap replicates to perform
216 #' @param by_group If \code{TRUE}, then bootstrap within each group if \code{df} is
217 #' a grouped tibble.
218 #'
219 #' @details This code originates from Hadley Wickham (with a few small
220 #' corrections) here:
221 #' \url{https://github.com/tidyverse/dplyr/issues/269}
222 #'
223 #' @export
224 #' @family deprecated
225 bootstrap <- function(df, m, by_group = FALSE) {
226 .Deprecated(
227 msg = "`bootstrap()` is deprecated and will be removed in an upcoming release of broom. See the rsample package instead."
228 )
229 n <- nrow(df)
230 attr(df, "indices") <-
231 if (by_group && !is.null(groups(df))) {
232 replicate(
233 m,
234 unlist(
235 lapply(
236 attr(df, "indices"),
237 function(x) {
238 sample(x, replace = TRUE)
239 }
240 ),
241 recursive = FALSE,
242 use.names = FALSE
243 ),
244 simplify = FALSE
245 )
246 } else {
247 replicate(
248 m,
249 sample(n, replace = TRUE) -
250 1,
251 simplify = FALSE
252 )
253 }
254 attr(df, "drop") <- TRUE
255 attr(df, "group_sizes") <- rep(n, m)
256 attr(df, "biggest_group_size") <- n
257 attr(df, "labels") <- data.frame(replicate = 1:m)
258 attr(df, "vars") <- list(quote(replicate))
259 class(df) <- c("grouped_df", "tbl_df", "tbl", "data.frame")
260 df
261 }
262
263 # fix_data_frame ----------------------------------------------------------
264
265 #' Ensure an object is a data frame, with rownames moved into a column
266 #'
267 #' This function is deprecated as of broom 0.7.0 and will be removed from
268 #' a future release. Please see \code{tibble::as_tibble}.
269 #'
270 #' @param x a data.frame or matrix
271 #' @param newnames new column names, not including the rownames
272 #' @param newcol the name of the new rownames column
273 #'
274 #' @return a data.frame, with rownames moved into a column and new column
275 #' names assigned
276 #' @family deprecated
277 #' @export
278 fix_data_frame <- function(x, newnames = NULL, newcol = "term") {
279 .Deprecated(
280 msg = "This function is deprecated as of broom 0.7.0 and will be removed from a future release. Please see tibble::as_tibble()."
281 )
282
283 if (!is.null(newnames) && length(newnames) != ncol(x)) {
284 cli::cli_abort(
285 "{.arg newnames} must be {.code NULL} or have length
286 equal to the number of columns."
287 )
288 }
289
290 if (all(rownames(x) == seq_len(nrow(x)))) {
291 # don't need to move rownames into a new column
292 ret <- data.frame(x, stringsAsFactors = FALSE)
293 if (!is.null(newnames)) {
294 colnames(ret) <- newnames
295 }
296 } else {
297 ret <- data.frame(
298 ...new.col... = rownames(x),
299 unrowname(x),
300 stringsAsFactors = FALSE
301 )
302 colnames(ret)[1] <- newcol
303 if (!is.null(newnames)) {
304 colnames(ret)[-1] <- newnames
305 }
306 }
307 as_tibble(ret)
308 }
309
310 # summary objects -----------------------------------------------------
311
312 #' (Deprecated) Tidy summaryDefault objects
313 #'
314 #' Tidiers for summaryDefault objects have been deprecated as of
315 #' broom 0.7.0 in favor of \code{skimr::skim()}.
316 #'
317 #' @param x A `summaryDefault` object, created by calling [summary()] on a
318 #' vector.
319 #' @template param_unused_dots
320 #'
321 #' @return A one-row [tibble::tibble] with columns:
322 #' \item{minimum}{Minimum value in original vector.}
323 #' \item{q1}{First quartile of original vector.}
324 #' \item{median}{Median of original vector.}
325 #' \item{mean}{Mean of original vector.}
326 #' \item{q3}{Third quartile of original vector.}
327 #' \item{maximum}{Maximum value in original vector.}
328 #' \item{na}{Number of `NA` values in original vector. Column present only
329 #' when original vector had at least one `NA` entry.}
330 #'
331 #'
332 #' @examples
333 #'
334 #' v <- rnorm(1000)
335 #' s <- summary(v)
336 #' s
337 #'
338 #' tidy(s)
339 #' glance(s)
340 #'
341 #' v2 <- c(v,NA)
342 #' tidy(summary(v2))
343 #'
344 #' @name summary_tidiers
345 #' @export
346 #' @family deprecated
347 tidy.summaryDefault <- function(x, ...) {
348 .Deprecated(
349 msg = "`tidy.summaryDefault()` is deprecated. Please use `skimr::skim()` instead."
350 )
351 ret <- as.data.frame(t(as.matrix(x)))
352 cnms <- c("minimum", "q1", "median", "mean", "q3", "maximum")
353 if (any(c("NA's", "NAs") %in% names(x))) {
354 cnms <- c(cnms, "na")
355 }
356 as_tibble(purrr::set_names(ret, cnms))
357 }
358
359 #' @rdname summary_tidiers
360 #' @export
361 #' @family deprecated
362 glance.summaryDefault <- tidy.summaryDefault
363
364 #' (Deprecated) Tidy ftable objects
365 #'
366 #' @description This function is deprecated. Please use [tibble::as_tibble()] instead.
367 #'
368 #' @param x An `ftable` object returned from [stats::ftable()].
369 #' @template param_unused_dots
370 #'
371 #' @return An ftable contains a "flat" contingency table. This melts it into a
372 #' [tibble::tibble] with one column for each variable, then a `Freq`
373 #' column.
374 #'
375 #' @export
376 #' @family deprecated
377 tidy.ftable <- function(x, ...) {
378 .Deprecated()
379 as_tibble(x)
380 }
381
382 #' (Deprecated) Tidy density objects
383 #'
384 #' @param x A `density` object returned from [stats::density()].
385 #' @template param_unused_dots
386 #'
387 #' @return A [tibble::tibble] with two columns: points `x` where the density
388 #' is estimated, and estimated density `y`.
389 #'
390 #' @export
391 #' @family deprecated
392 tidy.density <- function(x, ...) {
393 as_tibble(x[c("x", "y")])
394 }
395
396 #' (Deprecated) Tidy dist objects
397 #'
398 #' @param x A `dist` object returned from [stats::dist()].
399 #' @param diagonal Logical indicating whether or not to tidy the diagonal
400 #' elements of the distance matrix. Defaults to whatever was based to the
401 #' `diag` argument of [stats::dist()].
402 #' @param upper Logical indicating whether or not to tidy the upper half of
403 #' the distance matrix. Defaults to whatever was based to the
404 #' `upper` argument of [stats::dist()].
405 #' @template param_unused_dots
406 #'
407 #' @return A [tibble::tibble] with one row for each pair of items in the
408 #' distance matrix, with columns:
409 #'
410 #' \item{item1}{First item}
411 #' \item{item2}{Second item}
412 #' \item{distance}{Distance between items}
413 #'
414 #' @details If the distance matrix does not include an upper triangle and/or
415 #' diagonal, the tidied version will not either.
416 #'
417 #' @examples
418 #'
419 #' cars_dist <- dist(t(mtcars[, 1:4]))
420 #' cars_dist
421 #'
422 #' tidy(cars_dist)
423 #' tidy(cars_dist, upper = TRUE)
424 #' tidy(cars_dist, diagonal = TRUE)
425 #'
426 #' @export
427 #' @family deprecated
428 tidy.dist <- function(
429 x,
430 diagonal = attr(x, "Diag"),
431 upper = attr(x, "Upper"),
432 ...
433 ) {
434 ret <- as.matrix(x) |>
435 tibble::as_tibble(rownames = "item1") |>
436 tidyr::pivot_longer(cols = c(dplyr::everything(), -1)) |>
437 dplyr::rename(item2 = 2, distance = 3) |>
438 dplyr::mutate(item1 = as.factor(item1), item2 = as.factor(item2))
439
440 if (!upper) {
441 ret <- as.data.frame(ret)[!upper.tri(as.matrix(x)), ]
442 }
443
444 if (!diagonal) {
445 ret <- filter(ret, item1 != item2)
446 }
447 as_tibble(ret)
448 }
449
450 # vector tidiers ------------------------------------------------------
451 #' Tidy atomic vectors
452 #'
453 #' Vector tidiers are deprecated and will be removed from an upcoming release
454 #' of broom.
455 #'
456 #' Turn atomic vectors into data frames, where the names of the vector (if they
457 #' exist) are a column and the values of the vector are a column.
458 #'
459 #' @param x An object of class "numeric", "integer", "character", or "logical".
460 #' Most likely a named vector
461 #' @param ... Extra arguments (not used)
462 #'
463 #' @examples
464 #'
465 #' \dontrun{
466 #' x <- 1:5
467 #' names(x) <- letters[1:5]
468 #' tidy(x)
469 #' }
470 #'
471 #' @export
472 #' @rdname vector_tidiers
473 #' @family deprecated
474 tidy.numeric <- function(x, ...) {
475 .Deprecated()
476 if (!is.null(names(x))) {
477 tibble::tibble(names = names(x), x = unname(x))
478 } else {
479 tibble::tibble(x = x)
480 }
481 }
482
483 #' @export
484 #' @rdname vector_tidiers
485 #' @family deprecated
486 tidy.character <- tidy.default
487
488 #' @export
489 #' @rdname vector_tidiers
490 #' @family deprecated
491 tidy.logical <- function(x, ...) {
492 .Deprecated()
493 if (!is.null(names(x))) {
494 tibble::tibble(names = names(x), x = unname(x))
495 } else {
496 tibble::tibble(x = x)
497 }
498 }
499
500 # confint_tidy ----------------------------------------------------------------
501
502 #' (Deprecated) Calculate confidence interval as a tidy data frame
503 #'
504 #' This function is now deprecated and will be removed from a future
505 #' release of broom.
506 #'
507 #' Return a confidence interval as a tidy data frame. This directly wraps the
508 #' [confint()] function, but ensures it follows broom conventions:
509 #' column names of `conf.low` and `conf.high`, and no row names.
510 #'
511 #' `confint_tidy`
512 #'
513 #' @param x a model object for which [confint()] can be calculated
514 #' @param conf.level confidence level
515 #' @param func A function to compute a confidence interval for `x`. Calling
516 #' `func(x, level = conf.level, ...)` must return an object coercible to a
517 #' tibble. This dataframe like object should have to columns corresponding
518 #' the lower and upper bounds on the confidence interval.
519 #' @param ... extra arguments passed on to `confint`
520 #'
521 #' @return A tibble with two columns: `conf.low` and `conf.high`.
522 #'
523 #' @export
524 #' @family deprecated
525 confint_tidy <- function(x, conf.level = .95, func = stats::confint, ...) {
526 .Deprecated(
527 msg = "confint_tidy is now deprecated and will be removed from a future release of broom. Please use the applicable confint method."
528 )
529
530 # avoid "Waiting for profiling to be done..." message for some models
531 ci <- suppressMessages(func(x, level = conf.level, ...))
532
533 # protect against confidence intervals returned as named vectors
534 if (is.null(dim(ci))) {
535 ci <- matrix(ci, nrow = 1)
536 }
537
538 # remove rows that are all NA. *not the same* as na.omit which checks
539 # for any NA.
540 all_na <- apply(ci, 1, function(x) all(is.na(x)))
541 ci <- ci[!all_na, , drop = FALSE]
542 colnames(ci) <- c("conf.low", "conf.high")
543 as_tibble(ci)
544 }
545
546 # finish_glance -------------------------------------------------------
547 #' (Deprecated) Add logLik, AIC, BIC, and other common measurements to a
548 #' glance of a prediction
549 #'
550 #' This function is now deprecated in favor of using custom logic and
551 #' the appropriate \code{nobs()} method.
552 #'
553 #'
554 #' @param ret a one-row data frame (a partially complete glance)
555 #' @param x the prediction model
556 #'
557 #' @return a one-row data frame with additional columns added, such as
558 #' \item{logLik}{log likelihoods}
559 #' \item{AIC}{Akaike Information Criterion}
560 #' \item{BIC}{Bayesian Information Criterion}
561 #' \item{deviance}{deviance}
562 #' \item{df.residual}{residual degrees of freedom}
563 #'
564 #' @export
565 #' @family deprecated
566 finish_glance <- function(ret, x) {
567 .Deprecated(
568 msg = "finish_glance is now deprecated and will be removed from a future release of broom. Please only use the relevant `stats` functions for the given model type as needed."
569 )
570 ret$logLik <- tryCatch(as.numeric(stats::logLik(x)), error = function(e) NULL)
571 ret$AIC <- tryCatch(stats::AIC(x), error = function(e) NULL)
572 ret$BIC <- tryCatch(stats::BIC(x), error = function(e) NULL)
573
574 # special case for REML objects (better way?)
575 if (inherits(x, "lmerMod")) {
576 ret$deviance <- tryCatch(
577 stats::deviance(x, REML = FALSE),
578 error = function(e) NULL
579 )
580 } else {
581 ret$deviance <- tryCatch(stats::deviance(x), error = function(e) NULL)
582 }
583 ret$df.residual <- tryCatch(df.residual(x), error = function(e) NULL)
584
585 as_tibble(ret, rownames = NULL)
586 }