Debian Codegraph @

R/stats-anova.R

raw
1 #' @templateVar class anova
2 #' @template title_desc_tidy
3 #'
4 #' @param x An `anova` object, such as those created by [stats::anova()],
5 #' [car::Anova()], [car::leveneTest()], or [car::linearHypothesis()].
6 #' @template param_unused_dots
7 #'
8 #' @evalRd return_tidy(
9 #' "term",
10 #' "df",
11 #' "sumsq",
12 #' "meansq",
13 #' "statistic",
14 #' "p.value"
15 #' )
16 #'
17 #' @details
18 #' The `term` column of an ANOVA table can come with leading or
19 #' trailing whitespace, which this tidying method trims.
20 #'
21 #' For documentation on the tidier for [car::leveneTest()] output, see
22 #' [tidy.leveneTest()]
23 #'
24 # #' @examplesIf rlang::is_installed("car")
25 # unreplicable error on R-devel 4.5 (#1205)
26 #' @examplesIf FALSE
27 #'
28 #' # fit models
29 #' a <- lm(mpg ~ wt + qsec + disp, mtcars)
30 #' b <- lm(mpg ~ wt + qsec, mtcars)
31 #'
32 #' mod <- anova(a, b)
33 #'
34 #' # summarize model fit with tidiers
35 #' tidy(mod)
36 #' glance(mod)
37 #'
38 #' # car::linearHypothesis() example
39 #' library(car)
40 #' mod_lht <- linearHypothesis(a, "wt - disp")
41 #' tidy(mod_lht)
42 #' glance(mod_lht)
43 #'
44 #' @export
45 #' @family anova tidiers
46 #' @seealso [tidy()], [stats::anova()], [car::Anova()], [car::leveneTest()]
47 tidy.anova <- function(x, ...) {
48 # car::leveneTest returns an object of class `anova`
49 if (
50 !is.null(attr(x, "heading")) &&
51 isTRUE(grepl(
52 "Levene's Test for Homogeneity of Variance",
53 attr(x, "heading")
54 ))
55 ) {
56 return(tidy(structure(x, class = c("leveneTest", class(x))), ...))
57 }
58
59 # there are many possible column names that need to be transformed
60 renamers <- c(
61 "AIC" = "AIC", # merMod
62 "BIC" = "BIC", # merMod
63 "deviance" = "deviance", # merMod
64 "Deviance" = "deviance",
65 "logLik" = "logLik", # merMod
66 "Df" = "df",
67 "Chi.Df" = "df",
68 "Sum Sq" = "sumsq",
69 "Mean Sq" = "meansq",
70 "F value" = "statistic",
71 "Pr(>F)" = "p.value",
72 "Resid..Dev" = "residual.deviance",
73 "Resid..Df" = "df.residual",
74 "Res.Df" = "df.residual",
75 "RSS" = "rss",
76 "Sum of Sq" = "sumsq",
77 "F" = "statistic",
78 "Chisq" = "statistic",
79 "npar" = "npar",
80 "P(>|Chi|)" = "p.value",
81 "Pr(>|Chi|)" = "p.value",
82 "Pr(>Chi)" = "p.value",
83 "Pr..Chisq." = "p.value",
84 "Pr..Chi." = "p.value",
85 "p.value" = "p.value",
86 "Chi.sq" = "statistic",
87 "LR.Chisq" = "statistic",
88 "LR Chisq" = "statistic",
89 "edf" = "edf",
90 "Ref.df" = "ref.df",
91 "loglik" = "logLik",
92 ".rownames" = "term",
93 "-2*log(L)" = "minus2logL",
94 "X.2.log.L." = "minus2logL"
95 )
96
97 names(renamers) <- make.names(names(renamers))
98
99 ret <- as_augment_tibble(x)
100 colnames(ret) <- make.names(names(ret))
101
102 unknown_cols <- setdiff(colnames(ret), c("term", names(renamers)))
103 if (length(unknown_cols) > 0) {
104 cli::cli_warn(
105 "The column name{?s} {.field {unknown_cols}} in ANOVA output {?was/were}
106 not recognized or transformed."
107 )
108 }
109
110 colnames(ret) <- dplyr::recode(colnames(ret), !!!renamers)
111
112 # Special catch for car::linearHypothesis
113 x_attr <- attributes(x)
114 ## include "Model 1:", "Model 2:" (stats::anova()) and "mod1:", "mod2:"
115 ## (lme4::anova()), but *exclude* "Models:" (found in lme4::anova() header).
116 ## alternatively, could drop the first line of the header?
117 modstr <- "[Mm]od.*[0-9]+:"
118 mod_lines <- grep(modstr, x_attr$heading, value = TRUE)
119 if (!is.null(x_attr$value)) {
120 if (isTRUE(grepl("Linear hypothesis", x_attr$heading[[1]]))) {
121 # Drop unrestricted model (not interesting in linear hypothesis tests)
122 # Use formula to subset if available (e.g. with car::linearHypothesis)
123 if (length(mod_lines) != 0) {
124 idx <- sub(
125 "Model \\d*: ",
126 "",
127 strsplit(mod_lines, "\\nModel \\d*: ")[[1]]
128 )
129 idx <- idx != "restricted model"
130 ret <- ret[idx, , drop = FALSE]
131 }
132 hypothesis <- x_attr$heading[grep("=", x_attr$heading)]
133 ret_xtra <- data.frame(
134 term = gsub(" =.*", "", hypothesis),
135 null.value = as.numeric(gsub(".*= ", "", hypothesis)),
136 estimate = x_attr$value,
137 std.error = sqrt(as.numeric(diag(x_attr$vcov)))
138 )
139 row.names(ret_xtra) <- row.names(ret) <- NULL
140 ret_xtra$term <- gsub(" ", " ", ret_xtra$term) ## Occasional, annoying extra space
141 ret <- cbind(ret_xtra, ret) |>
142 dplyr::select(
143 term,
144 null.value,
145 estimate,
146 std.error,
147 statistic,
148 p.value,
149 dplyr::everything()
150 )
151 } else {
152 ## If model formulas (e.g. from car::linearHypothesis) weren't available,
153 ## just add the term and response columns
154 response <- sub(
155 ".*: ",
156 "",
157 strsplit(x_attr$heading[grep("Response", x_attr$heading)], "\n")[[1]]
158 )
159 term <- row.names(ret)
160 ret < cbind(cbind(term, ret), response)
161 row.names(ret) <- NULL
162 }
163 } else if ((!"term" %in% colnames(ret)) & length(mod_lines) != 0) {
164 mod_lines <- gsub("\n ", "", mod_lines)
165 mods <- sub(".*: ", "", strsplit(mod_lines, "\n")[[1]])
166 ret <- cbind(term = mods, ret)
167 } else if ((!"term" %in% colnames(ret)) & !is.null(row.names(ret))) {
168 ret <- cbind(term = row.names(ret), ret)
169 row.names(ret) <- NULL
170 }
171
172 if ("term" %in% names(ret)) {
173 # if rows had names, strip whitespace in them
174 ret <- mutate(ret, term = stringr::str_trim(term))
175 }
176
177 as_tibble(ret)
178 }
179
180
181 #' @templateVar class anova
182 #' @template title_desc_glance
183 #'
184 #' @inherit tidy.anova params examples
185 #'
186 #' @note
187 #' Note that the output of `glance.anova()` will vary depending on the initializing
188 #' anova call. In some cases, it will just return an empty data frame. In other
189 #' cases, `glance.anova()` may return columns that are also common to
190 #' `tidy.anova()`. This is partly to preserve backwards compatibility with early
191 #' versions of `broom`, but also because the underlying anova model yields
192 #' components that could reasonably be interpreted as goodness-of-fit summaries
193 #' too.
194 #'
195 #' @evalRd return_glance(
196 #' "deviance",
197 #' "df.residual"
198 #' )
199 #'
200 #' @export
201 #' @seealso [glance()]
202 #' @family anova tidiers
203 glance.anova <- function(x, ...) {
204 # we'll only grab a subset of columns (and the "statistic" cols are just for
205 # subsetting rows)
206 renamers <- c(
207 "F" = "statistic",
208 "Chisq" = "statistic",
209 "F value" = "statistic",
210 "Chi.sq" = "statistic",
211 "LR.Chisq" = "statistic",
212 "LR Chisq" = "statistic",
213 "Res.Df" = "df.residual",
214 "RSS" = "deviance" ## Note: note "rss"
215 )
216
217 names(renamers) <- make.names(names(renamers))
218
219 ret <- as_augment_tibble(x)
220 colnames(ret) <- make.names(names(ret))
221
222 colnames(ret) <- dplyr::recode(colnames(ret), !!!renamers)
223
224 if (any(c("deviance", "df.residual") %in% colnames(ret))) {
225 ret <- ret[!is.na(ret$statistic), ]
226 ret <- ret[, c("deviance", "df.residual")]
227 } else {
228 ret <- data.frame()
229 }
230
231 as_tibble(ret)
232 }
233
234
235 #' @templateVar class aov
236 #' @template title_desc_tidy
237 #'
238 #' @param x An `aov` object, such as those created by [stats::aov()].
239 #' @template param_unused_dots
240 #'
241 #' @inherit tidy.anova return details
242 #'
243 #' @examples
244 #'
245 #' a <- aov(mpg ~ wt + qsec + disp, mtcars)
246 #' tidy(a)
247 #' @export
248 #' @family anova tidiers
249 #' @param intercept A logical indicating whether information on the intercept
250 #' ought to be included. Passed to [stats::summary.aov()].
251 #' @seealso [tidy()], [stats::aov()]
252 tidy.aov <- function(x, intercept = FALSE, ...) {
253 summary(x, intercept = intercept)[[1]] |>
254 tibble::as_tibble(rownames = "term") |>
255 dplyr::mutate("term" = stringr::str_trim(term)) |>
256 rename2(
257 "df" = "Df",
258 "sumsq" = "Sum Sq",
259 "meansq" = "Mean Sq",
260 "statistic" = "F value",
261 "p.value" = "Pr(>F)"
262 )
263 }
264
265
266 #' @templateVar class lm
267 #' @template title_desc_glance
268 #'
269 #' @inherit tidy.aov params examples
270 #'
271 #' @note
272 #' Note that `tidy.aov()` now contains the numerator and denominator degrees of
273 #' freedom, which were included in the output of `glance.aov()` in some
274 #' previous versions of the package.
275 #'
276 #' @evalRd return_glance(
277 #' "logLik",
278 #' "AIC",
279 #' "BIC",
280 #' "deviance",
281 #' "nobs"
282 #' )
283 #'
284 #' @export
285 #' @seealso [glance()]
286 #' @family anova tidiers
287 glance.aov <- function(x, ...) {
288 lm_sum <- summary(lm(x))
289
290 as_glance_tibble(
291 logLik = as.numeric(stats::logLik(x)),
292 AIC = stats::AIC(x),
293 BIC = stats::BIC(x),
294 deviance = stats::deviance(x),
295 nobs = stats::nobs(x),
296 r.squared = lm_sum$r.squared,
297 na_types = "rrrrir"
298 )
299 }
300
301 #' @templateVar class aovlist
302 #' @template title_desc_tidy
303 #'
304 #' @param x An `aovlist` objects, such as those created by [stats::aov()].
305 #' @template param_unused_dots
306 #'
307 #' @evalRd return_tidy(
308 #' "term",
309 #' "df",
310 #' "sumsq",
311 #' "meansq",
312 #' "statistic",
313 #' "p.value",
314 #' "stratum"
315 #' )
316 #'
317 #' @inherit tidy.anova details
318 #'
319 #' @examples
320 #'
321 #' a <- aov(mpg ~ wt + qsec + Error(disp / am), mtcars)
322 #' tidy(a)
323 #' @export
324 #' @family anova tidiers
325 #' @seealso [tidy()], [stats::aov()]
326 tidy.aovlist <- function(x, ...) {
327 # must filter out Intercept stratum since it has no dimensions
328 if (names(x)[1L] == "(Intercept)") {
329 x <- x[-1L]
330 }
331
332 ret <- map_df(x, tidy, .id = "stratum")
333
334 # get rid of leading and trailing whitespace in term and stratum columns
335 ret <- ret |>
336 mutate(
337 term = stringr::str_trim(term),
338 stratum = stringr::str_trim(stratum)
339 )
340
341 as_tibble(ret)
342 }
343
344
345 #' @templateVar class manova
346 #' @template title_desc_tidy
347 #'
348 #' @param x A `manova` object return from [stats::manova()].
349 #' @param test One of "Pillai" (Pillai's trace), "Wilks" (Wilk's lambda),
350 #' "Hotelling-Lawley" (Hotelling-Lawley trace) or "Roy" (Roy's greatest root)
351 #' indicating which test statistic should be used. Defaults to "Pillai".
352 #' @inheritDotParams stats::summary.manova
353 #'
354 #' @evalRd return_tidy(
355 #' "term",
356 #' "num.df",
357 #' "den.df",
358 #' "statistic",
359 #' "p.value",
360 #' pillai = "Pillai's trace.",
361 #' wilks = "Wilk's lambda.",
362 #' hl = "Hotelling-Lawley trace.",
363 #' roy = "Roy's greatest root."
364 #' )
365 #'
366 #'
367 #' @details Depending on which test statistic is specified only one of `pillai`,
368 #' `wilks`, `hl` or `roy` is included.
369 #'
370 #' @examples
371 #'
372 #' npk2 <- within(npk, foo <- rnorm(24))
373 #' m <- manova(cbind(yield, foo) ~ block + N * P * K, npk2)
374 #' tidy(m)
375 #' @export
376 #' @seealso [tidy()], [stats::summary.manova()]
377 #' @family anova tidiers
378 tidy.manova <- function(x, test = "Pillai", ...) {
379 test.pos <- pmatch(
380 test,
381 c(
382 "Pillai",
383 "Wilks",
384 "Hotelling-Lawley",
385 "Roy"
386 )
387 )
388 test.name <- c("pillai", "wilks", "hl", "roy")[test.pos]
389
390 as_tidy_tibble(
391 summary(x, test = test, ...)$stats,
392 new_names = c("df", test.name, "statistic", "num.df", "den.df", "p.value")
393 )
394 }
395
396 #' @templateVar class TukeyHSD
397 #' @template title_desc_tidy
398 #'
399 #' @param x A `TukeyHSD` object return from [stats::TukeyHSD()].
400 #' @template param_unused_dots
401 #'
402 #' @evalRd return_tidy(
403 #' "term",
404 #' "contrast",
405 #' "null.value",
406 #' "estimate",
407 #' "conf.low",
408 #' "conf.high",
409 #' "adj.p.value"
410 #' )
411 #'
412 #' @examples
413 #'
414 #' fm1 <- aov(breaks ~ wool + tension, data = warpbreaks)
415 #' thsd <- TukeyHSD(fm1, "tension", ordered = TRUE)
416 #' tidy(thsd)
417 #'
418 #' # may include comparisons on multiple terms
419 #' fm2 <- aov(mpg ~ as.factor(gear) * as.factor(cyl), data = mtcars)
420 #' tidy(TukeyHSD(fm2))
421 #' @export
422 #' @seealso [tidy()], [stats::TukeyHSD()]
423 #' @family anova tidiers
424 tidy.TukeyHSD <- function(x, ...) {
425 purrr::map_df(
426 x,
427 function(e) {
428 null.value <- rep(0, nrow(e))
429 e <- cbind(null.value, e)
430 as_tidy_tibble(
431 e,
432 new_names = c(
433 "null.value",
434 "estimate",
435 "conf.low",
436 "conf.high",
437 "adj.p.value"
438 ),
439 new_column = "contrast"
440 )
441 },
442 .id = "term"
443 )
444 }