Debian Codegraph @

R/utilities.R

raw
1 # Rename only those columns in a data frame that are present. Example:
2 #
3 # rename2(
4 # tibble(dog = 1),
5 # cat = dog,
6 # mouse = gerbil
7 # )
8 #
9 rename2 <- function(.data, ...) {
10 dots <- quos(...)
11 present <- purrr::keep(dots, ~ quo_name(.x) %in% colnames(.data))
12 rename(.data, !!!present)
13 }
14
15 exponentiate <- function(data, col = "estimate") {
16 data <- data |> mutate(across(all_of(col), exp))
17
18 if ("conf.low" %in% colnames(data)) {
19 data <- data |> mutate(across(c(conf.low, conf.high), exp))
20 }
21
22 data
23 }
24
25 #' Coerce a data frame to a tibble
26 #'
27 #' A thin wrapper around [tibble::as_tibble()], except checks for
28 #' rownames and adds them to a new column `.rownames` if they are
29 #' interesting (i.e. more than `1, 2, 3, ...`). This function is
30 #' meant for use inside of `augment.*` methods.
31 #'
32 #' @param data A [base::data.frame()] or [tibble::tibble()].
33 #'
34 #' @return A `tibble` potentially with a `.rownames` column
35 #' @noRd
36 #'
37 as_augment_tibble <- function(
38 data,
39 arg = caller_arg(data),
40 call = caller_env()
41 ) {
42 if (inherits(data, "matrix") & is.null(colnames(data))) {
43 cli::cli_abort(c(
44 "{.arg {arg}} is an unnamed matrix.",
45 "i" = "Please supply a matrix or data frame with column names."
46 ))
47 }
48
49 tryCatch(
50 df <- as_tibble(data),
51 error = function(cnd) {
52 cli::cli_abort(
53 c(
54 "Could not coerce {.arg {arg}} to a tibble.",
55 "i" = "Try explicitly passing a data frame to either the {.arg data} or
56 {.arg newdata} argument."
57 ),
58 call = call
59 )
60 }
61 )
62
63 if (has_rownames(data)) {
64 df <- tibble::add_column(df, .rownames = rownames(data), .before = TRUE)
65 }
66 df
67 }
68
69 # adapted from ps:::is_cran_check()
70 is_cran_check <- function() {
71 if (identical(Sys.getenv("NOT_CRAN"), "true")) {
72 FALSE
73 } else {
74 Sys.getenv("_R_CHECK_PACKAGE_NAME_", "") != ""
75 }
76 }
77
78 #' Convert a data.frame or matrix to a tibble
79 #'
80 #' This function is meant for use inside `tidy.*` methods.
81 #'
82 #' @param x a data.frame or matrix
83 #' @param new_names new column names, not including the rownames
84 #' @param new_col the name of the new rownames column
85 #'
86 #' @return a tibble with rownames moved into a column and new column
87 #' names assigned
88 #' @noRd
89 as_tidy_tibble <- function(x, new_names = NULL, new_column = "term") {
90 if (!is.null(new_names) && length(new_names) != ncol(x)) {
91 cli::cli_abort(
92 "{.arg new names} must be {.code NULL} or have length equal to
93 number of columns ({ncol(data)})."
94 )
95 }
96
97 ret <- x
98
99 # matrices will take setNames by element, so rename conditionally
100 if (!is.null(new_names)) {
101 if (inherits(x, "data.frame")) {
102 ret <- setNames(x, new_names)
103 } else {
104 colnames(ret) <- new_names
105 }
106 }
107
108 if (all(rownames(x) == seq_len(nrow(x)))) {
109 # don't need to move rownames into a new column
110 tibble::as_tibble(ret)
111 } else {
112 # don't use tibble rownames to col because of name repairing
113 dplyr::bind_cols(
114 !!new_column := rownames(x),
115 tibble::as_tibble(ret)
116 )
117 }
118 }
119
120 #' @param x A list of data.frames or matrices
121 #' @param ... Extra arguments to pass to as_tidy_tibble
122 #' @param id_column The name of the column giving the name of each
123 #' element in `x`
124 #' @noRd
125 map_as_tidy_tibble <- function(x, ..., id_column = "component") {
126 purrr::map_df(x, as_tidy_tibble, ..., .id = id_column)
127 }
128
129 # copied from modeltests. re-export if at some we Import modeltests rather
130 # than suggest it
131 has_rownames <- function(df) {
132 if (tibble::is_tibble(df)) {
133 return(FALSE)
134 }
135 any(rownames(df) != as.character(1:nrow(df)))
136 }
137
138 na_types_dict <- list(
139 "r" = NA_real_,
140 "i" = rlang::na_int,
141 "c" = NA_character_,
142 "l" = rlang::na_lgl
143 )
144
145 # a function that converts a string to a vector of NA types.
146 # e.g. "rri" -> c(NA_real_, NA_real_, rlang::na_int)
147 parse_na_types <- function(s) {
148 positions <- purrr::map(
149 stringr::str_split(s, pattern = ""),
150 match,
151 table = names(na_types_dict)
152 ) |>
153 unlist()
154
155 na_types_dict[positions] |>
156 unlist() |>
157 unname()
158 }
159
160 # a function that, given named arguments, will make a one-row
161 # tibble, switching out NULLs for the appropriate NA type.
162 as_glance_tibble <- function(..., na_types) {
163 cols <- list(...)
164
165 if (length(cols) != stringr::str_length(na_types)) {
166 cli::cli_abort(
167 "The number of columns provided does not match the number of
168 column {.emph types} provided."
169 )
170 }
171
172 na_types_long <- parse_na_types(na_types)
173
174 entries <- purrr::map2(
175 cols,
176 na_types_long,
177 function(.x, .y) {
178 if (length(.x) == 0) .y else .x
179 }
180 )
181
182 tibble::as_tibble_row(entries)
183 }
184
185 # strip rownames from a data frame
186 unrowname <- function(x) {
187 rownames(x) <- NULL
188 x
189 }
190
191 #' Add fitted values, residuals, and other common outputs to
192 #' an augment call
193 #'
194 #' `augment_columns` is intended for use in the internals of `augment` methods
195 #' only and is exported for developers extending the broom package. Please
196 #' instead use [augment()] to appropriately make use of the functionality
197 #' in `augment_columns()`.
198 #'
199 #' Note that, in the case that a `residuals()` or `influence()` generic is
200 #' not implemented for the supplied model `x`, the function will fail quietly.
201 #'
202 #' @param x a model
203 #' @param data original data onto which columns should be added
204 #' @param newdata new data to predict on, optional
205 #' @param type Type of prediction and residuals to compute
206 #' @param type.predict Type of prediction to compute; by default
207 #' same as `type`
208 #' @param type.residuals Type of residuals to compute; by default
209 #' same as `type`
210 #' @param se.fit Value to pass to predict's `se.fit`, or NULL for
211 #' no value. Ignored for model types that do not accept an `se.fit`
212 #' argument
213 #' @param ... extra arguments (not used)
214 #'
215 #' @export
216 augment_columns <- function(
217 x,
218 data,
219 newdata = NULL,
220 type,
221 type.predict = type,
222 type.residuals = type,
223 se.fit = TRUE,
224 ...
225 ) {
226 notNAs <- function(o) {
227 if (is.null(o) || all(is.na(o))) NULL else o
228 }
229
230 residuals0 <- purrr::possibly(stats::residuals, NULL)
231 influence0 <- purrr::possibly(stats::influence, NULL)
232 cooks.distance0 <- purrr::possibly(stats::cooks.distance, NULL)
233 rstandard0 <- purrr::possibly(stats::rstandard, NULL)
234 predict0 <- purrr::possibly(stats::predict, NULL)
235
236 # call predict with arguments
237 args <- list(x)
238 if (!is.null(newdata)) {
239 args$newdata <- newdata
240 }
241 if (!missing(type.predict)) {
242 args$type <- type.predict[1]
243 }
244 if (!inherits(x, "betareg")) {
245 args$se.fit <- se.fit
246 }
247 args <- c(args, list(...))
248
249 if ("panelmodel" %in% class(x)) {
250 # work around for panel models (plm)
251 # stat::predict() returns wrong fitted values when applied to random or
252 # fixed effect panel models [plm(..., model="random"), plm(, ..., model="within")]
253 # It works only for pooled OLS models (plm( ..., model="pooling"))
254 pred <- model.frame(x)[, 1] - residuals(x)
255 } else {
256 # suppress warning: geeglm objects complain about predict being used
257 pred <- suppressWarnings(do.call(predict0, args))
258 }
259
260 if (is.null(pred)) {
261 # try "fitted" instead- some objects don't have "predict" method
262 pred <- do.call(stats::fitted, args)
263 }
264
265 if (is.list(pred)) {
266 ret <- data.frame(.fitted = as.vector(pred$fit))
267 ret$.se.fit <- as.vector(pred$se.fit)
268 } else {
269 ret <- data.frame(.fitted = as.vector(pred))
270 }
271
272 na_action <- if (isS4(x)) {
273 attr(stats::model.frame(x), "na.action")
274 } else {
275 stats::na.action(x)
276 }
277
278 if (missing(newdata) || is.null(newdata)) {
279 if (!missing(type.residuals)) {
280 ret$.resid <- residuals0(x, type = type.residuals)
281 } else {
282 ret$.resid <- residuals0(x)
283 }
284
285 infl <- influence0(x, do.coef = FALSE)
286 if (!is.null(infl)) {
287 if (inherits(x, "gam")) {
288 ret$.hat <- infl
289 ret$.sigma <- NA
290 } else {
291 zero_weights <- "weights" %in%
292 names(x) &&
293 any(zero_weight_inds <- abs(x$weights) < .Machine$double.eps^0.5)
294 if (zero_weights) {
295 ret[c(".hat", ".sigma")] <- 0
296 ret$.hat[!zero_weight_inds] <- infl$hat
297 ret$.sigma[!zero_weight_inds] <- infl$sigma
298 } else {
299 ret$.hat <- infl$hat
300 ret$.sigma <- infl$sigma
301 }
302 }
303 }
304
305 # if cooksd and rstandard can be computed and aren't all NA
306 # (as they are in rlm), do so
307 ret$.cooksd <- notNAs(cooks.distance0(x))
308 ret$.std.resid <- notNAs(rstandard0(x))
309
310 original <- data
311
312 if (inherits(na_action, "exclude")) {
313 # check if values are missing
314 if (length(stats::residuals(x)) > nrow(data)) {
315 cli::cli_warn(
316 c(
317 "When fitting with {.code na.exclude}, rows with {.code NA}s in
318 original data will be dropped unless those rows are provided
319 in the {.arg data} argument."
320 )
321 )
322 }
323 }
324 } else {
325 original <- newdata
326 }
327
328 if (is.null(na_action) || nrow(original) == nrow(ret)) {
329 # no NAs were left out; we can simply recombine
330 original <- as_augment_tibble(original)
331 return(as_tibble(cbind(original, ret)))
332 } else if (inherits(na_action, "omit")) {
333 # if the option is "omit", drop those rows from the data
334 original <- as_augment_tibble(original)
335 original <- original[-na_action, ]
336 return(as_tibble(cbind(original, ret)))
337 }
338
339 # add .rownames column to merge the results with the original; resilent to NAs
340 ret$.rownames <- rownames(ret)
341 original$.rownames <- rownames(original)
342 ret <- merge(original, ret, by = ".rownames")
343
344 # reorder to line up with original
345 ret <- ret[order(match(ret$.rownames, rownames(original))), ]
346
347 rownames(ret) <- NULL
348 # if rownames are just the original 1...n, they can be removed
349 if (all(ret$.rownames == seq_along(ret$.rownames))) {
350 ret$.rownames <- NULL
351 }
352
353 as_tibble(ret)
354 }
355
356 response <- function(object, newdata = NULL, has_response) {
357 if (!has_response) {
358 return(NULL)
359 }
360
361 res <-
362 tryCatch(
363 model.response(model.frame(
364 terms(object),
365 data = newdata,
366 na.action = na.pass
367 )),
368 error = function(e) NULL
369 )
370
371 if (is.null(res)) {
372 res <- model.response(model.frame(object))
373 }
374
375 res
376 }
377
378 data_error <- function(cnd, call = caller_env()) {
379 cli::cli_abort(
380 "Must specify either {.arg data} or {.arg newdata} argument.",
381 call = call
382 )
383 }
384
385 safe_response <- purrr::possibly(response, NULL)
386
387
388 # in weighted regressions, influence measures should be zero for
389 # data points with zero weight
390 # helper for augment.lm and augment.glm
391 add_hat_sigma_cols <- function(df, x, infl) {
392 df$.hat <- 0
393 df$.sigma <- 0
394 df$.cooksd <- 0
395 df$.std.resid <- NA
396
397 w <- x$weights
398 nonzero_idx <- if (is.null(w)) seq_along(df$.hat) else which(w != 0)
399
400 df$.hat[nonzero_idx] <- infl$hat |> unname()
401 df$.sigma[nonzero_idx] <- infl$sigma |> unname()
402 df$.std.resid[nonzero_idx] <- rstandard(x, infl = infl) |> unname()
403 df$.cooksd[nonzero_idx] <- cooks.distance(x, infl = infl) |> unname()
404 df
405 }
406
407
408 # adds only the information that can be defined for newdata. no influence
409 # measure of anything fun like goes here.
410 #
411 # add .fitted column
412 # add .resid column if response is present
413 # deal with rownames and convert to tibble as necessary
414 # add .se.fit column if present
415 # be *incredibly* careful that the ... are passed correctly
416 augment_newdata <- function(x, data, newdata, .se_fit, interval = NULL, ...) {
417 passed_newdata <- !is.null(newdata)
418 df <- if (passed_newdata) newdata else data
419 df <- as_augment_tibble(df)
420 # interval <- match.arg(interval)
421 # check if response variable is in newdata, if relevant:
422 if (!is.null(x$terms) & inherits(x$terms, "formula")) {
423 has_response <-
424 # TRUE if response includes a function call and is in column names,
425 # usually with no `data` or `newdata` supplied,
426 # and `data` defaults to `model_frame(x)`
427 rlang::as_label(rlang::f_lhs(x$terms)) %in%
428 names(df) ||
429 # TRUE if the response variable itself is in column names
430 all.vars(x$terms)[1] %in% names(df)
431 } else {
432 has_response <- FALSE
433 }
434
435 # NOTE: It is important use predict(x, newdata = newdata) rather than
436 # predict(x, newdata = df). This is to avoid an edge case breakage
437 # when augment is called with no data argument, so that data is
438 # model.frame(x). When data = model.frame(x) and the model formula
439 # contains a term like `log(x)`, the predict method will break. Luckily,
440 # predict(x, newdata = NULL) works perfectly well in this case.
441 #
442 # The current code relies on predict(x, newdata = NULL) functioning
443 # equivalently to predict(x, newdata = data). An alternative would be to use
444 # fitted(x) instead, although this may not play well with missing data,
445 # and may behave like na.action = na.omit rather than na.action = na.pass.
446
447 # This helper *should not* be used for predict methods that do not have
448 # an na.pass argument
449
450 if (.se_fit) {
451 pred_obj <- predict(
452 x,
453 newdata = newdata,
454 na.action = na.pass,
455 se.fit = .se_fit,
456 interval = interval,
457 ...
458 )
459 if (is.null(interval) || interval == "none") {
460 df$.fitted <- pred_obj$fit |> unname()
461 } else {
462 df$.fitted <- pred_obj$fit[, "fit"]
463 df$.lower <- pred_obj$fit[, "lwr"]
464 df$.upper <- pred_obj$fit[, "upr"]
465 }
466
467 # a couple possible names for the standard error element of the list
468 # se.fit: lm, glm
469 # se: loess
470 se_idx <- which(names(pred_obj) %in% c("se.fit", "se"))
471 df$.se.fit <- pred_obj[[se_idx]]
472 } else if (!is.null(interval) && interval != "none") {
473 pred_obj <- predict(
474 x,
475 newdata = newdata,
476 na.action = na.pass,
477 se.fit = FALSE,
478 interval = interval,
479 ...
480 )
481 df$.fitted <- pred_obj[, "fit"]
482 df$.lower <- pred_obj[, "lwr"]
483 df$.upper <- pred_obj[, "upr"]
484 } else if (passed_newdata) {
485 if (is.null(interval) || interval == "none") {
486 df$.fitted <- predict(x, newdata = newdata, na.action = na.pass, ...) |>
487 unname()
488 } else {
489 pred_obj <- predict(
490 x,
491 newdata = newdata,
492 na.action = na.pass,
493 interval = interval,
494 ...
495 )
496 df$.fitted <- pred_obj$fit[, "fit"]
497 df$.lower <- pred_obj$fit[, "lwr"]
498 df$.upper <- pred_obj$fit[, "upr"]
499 }
500 } else {
501 if (is.null(interval) || interval == "none") {
502 df$.fitted <- predict(x, na.action = na.pass, ...) |>
503 unname()
504 } else {
505 pred_obj <- predict(
506 x,
507 newdata = newdata,
508 na.action = na.pass,
509 interval = interval,
510 ...
511 )
512 df$.fitted <- pred_obj$fit[, "fit"]
513 df$.lower <- pred_obj$fit[, "lwr"]
514 df$.upper <- pred_obj$fit[, "upr"]
515 }
516 }
517
518 resp <- safe_response(x, df, has_response)
519
520 if (!is.null(resp) && is.numeric(resp)) {
521 df$.resid <- (resp - df$.fitted) |> unname()
522 }
523
524 df
525 }
526
527 # this exists to avoid the single predictor gotcha
528 # this version adds a terms column
529 broom_confint <- function(x, ...) {
530 # warn on arguments silently being ignored
531 rlang::check_dots_used()
532 ci <- suppressMessages(confint(x, ...))
533
534 # confint called on models with a single predictor
535 # often returns a named vector rather than a matrix :(
536
537 if (is.null(dim(ci))) {
538 ci <- matrix(ci, nrow = 1)
539 }
540
541 ci <- as_tibble(ci)
542 names(ci) <- c("term", "conf.low", "conf.high")
543 ci
544 }
545
546 # this version adds a terms column
547 broom_confint_terms <- function(x, ...) {
548 # warn on arguments silently being ignored
549 rlang::check_dots_used()
550 ci <- suppressMessages(confint(x, ...))
551
552 # confint called on models with a single predictor
553 # often returns a named vector rather than a matrix :(
554
555 if (is.null(dim(ci))) {
556 ci <- matrix(ci, nrow = 1)
557 rownames(ci) <- names(coef(x))[1]
558 }
559
560 ci <- as_tibble(ci, rownames = "term", .name_repair = "minimal")
561 names(ci) <- c("term", "conf.low", "conf.high")
562 ci
563 }
564
565 # warn when models subclasses glm/lm and do not have their own dedicated tidiers.
566 warn_on_subclass <- function(x, tidier) {
567 if (length(class(x)) > 1 && class(x)[1] != "glm") {
568 subclass <- class(x)[1]
569 dispatched_method <- class(x)[class(x) %in% c("glm", "lm")][1]
570
571 rlang::warn(
572 paste0(
573 "The `",
574 tidier,
575 "()` method for objects of class `",
576 subclass,
577 "` is not maintained by the broom team, and is only supported through ",
578 "the `",
579 dispatched_method,
580 "` tidier method. Please be cautious in interpreting and reporting ",
581 "broom output.\n"
582 ),
583 .frequency = "once",
584 .frequency_id = subclass
585 )
586 }
587 }
588
589 #' @importFrom utils globalVariables
590 globalVariables(
591 c(
592 ":=",
593 ".",
594 ".fitted",
595 ".id",
596 ".resid",
597 ".rownames",
598 ".tau",
599 "aic",
600 "alternative",
601 "AME",
602 "bic",
603 "chosen",
604 "ci.lower",
605 "ci.upper",
606 "column",
607 "column1",
608 "column2",
609 "comp",
610 "compareVersion",
611 "comparison",
612 "conf.high",
613 "conf.low",
614 "contrast",
615 "cook.d",
616 "cov.r",
617 "cutoffs",
618 "data",
619 "delete.response",
620 "dffits",
621 "dfbetas",
622 "df.residual",
623 "distance",
624 "effect",
625 "est",
626 "estimate",
627 "expCIWidth",
628 "fit",
629 "GCV",
630 "group",
631 "group1",
632 "group2",
633 "hat",
634 "id",
635 "idx",
636 "index",
637 "Intercept",
638 "item1",
639 "item2",
640 "key",
641 "lavInspect",
642 "lambda",
643 "level",
644 "linpred",
645 "lhs",
646 "lm",
647 "loading",
648 "lower",
649 "method",
650 "Method",
651 "N",
652 "nobs",
653 "norig",
654 "null.value",
655 "objs",
656 "obs",
657 "op",
658 "p",
659 "p.value",
660 "packageVersion",
661 "PC",
662 "percent",
663 "P-perm (1-tailed)",
664 "Pr(Chi)",
665 "probabilities",
666 "pvalue",
667 "QE.del",
668 "rd_roclet",
669 "rhs",
670 "rmsea.ci.upper",
671 "rowname",
672 "rstudent",
673 "se",
674 "SE",
675 "series",
676 "Slope",
677 "stat",
678 "statistic",
679 "std.dev",
680 "std.error",
681 "step",
682 "stratum",
683 "surv",
684 "tau2.del",
685 "term",
686 "type",
687 "upper",
688 "value",
689 "Var1",
690 "Var2",
691 "variable",
692 "wald.test",
693 "weight",
694 "where",
695 "y",
696 "z"
697 )
698 )
699
700 # a gentler version of dots checking that, given a dots entry to
701 # look for, will warn if that entry is in the dots.
702 # in broom, this is used for exponentiate (in tidy) and newdata (in augment).
703 check_ellipses <- function(arg, fn, cls, ...) {
704 dots <- rlang::enquos(...)
705
706 if (arg %in% names(dots)) {
707 rlang::warn(paste0(
708 "The `",
709 arg,
710 "` argument is not supported in the `",
711 fn,
712 "()` method for `",
713 cls,
714 "` objects and will be ignored."
715 ))
716 }
717
718 invisible(NULL)
719 }