Debian Codegraph @

R/stats-htest.R

raw
1 #' @templateVar class htest
2 #' @template title_desc_tidy_glance
3 #'
4 #' @param x An `htest` objected, such as those created by [stats::cor.test()],
5 #' [stats::t.test()], [stats::wilcox.test()], [stats::chisq.test()], etc.
6 #' @template param_unused_dots
7 #'
8 #' @evalRd return_tidy(
9 #' "estimate",
10 #' "statistic",
11 #' "p.value",
12 #' "parameter",
13 #' "conf.low",
14 #' "conf.high",
15 #' "estimate1",
16 #' "estimate2",
17 #' "method",
18 #' "alternative"
19 #' )
20 #'
21 #' @examples
22 #'
23 #' tt <- t.test(rnorm(10))
24 #'
25 #' tidy(tt)
26 #'
27 #' # the glance output will be the same for each of the below tests
28 #' glance(tt)
29 #'
30 #' tt <- t.test(mpg ~ am, data = mtcars)
31 #'
32 #' tidy(tt)
33 #'
34 #' wt <- wilcox.test(mpg ~ am, data = mtcars, conf.int = TRUE, exact = FALSE)
35 #'
36 #' tidy(wt)
37 #'
38 #' ct <- cor.test(mtcars$wt, mtcars$mpg)
39 #'
40 #' tidy(ct)
41 #'
42 #' chit <- chisq.test(xtabs(Freq ~ Sex + Class, data = as.data.frame(Titanic)))
43 #'
44 #' tidy(chit)
45 #' augment(chit)
46 #'
47 #' @aliases htest_tidiers
48 #' @export
49 #' @family htest tidiers
50 #' @seealso [tidy()], [stats::cor.test()], [stats::t.test()],
51 #' [stats::wilcox.test()], [stats::chisq.test()]
52 tidy.htest <- function(x, ...) {
53 ret <- x[c("estimate", "statistic", "p.value", "parameter")]
54
55 # estimate may have multiple values
56 if (length(ret$estimate) > 1) {
57 names(ret$estimate) <- paste0("estimate", seq_along(ret$estimate))
58 ret <- c(ret$estimate, ret)
59 ret$estimate <- NULL
60
61 # special case: in a t-test, estimate = estimate1 - estimate2
62 if (x$method %in% c("Welch Two Sample t-test", " Two Sample t-test")) {
63 ret <- c(estimate = ret$estimate1 - ret$estimate2, ret)
64 }
65 }
66
67 # parameter may have multiple values as well, such as oneway.test
68 if (length(x$parameter) > 1) {
69 ret$parameter <- NULL
70 if (is.null(names(x$parameter))) {
71 cli::cli_warn(
72 "Multiple unnamed parameters in hypothesis test; dropping them."
73 )
74 } else {
75 # rename num df to num.df and denom df to denom.df
76 np <- names(x$parameter)
77 np <- stringr::str_replace(np, "num df", "num.df")
78 np <- stringr::str_replace(np, "denom df", "den.df")
79 names(x$parameter) <- np
80
81 cli::cli_inform("Multiple parameters; naming those columns {np}.")
82
83 ret <- append(ret, x$parameter, after = 1)
84 }
85 }
86
87 ret <- purrr::compact(ret)
88 if (!is.null(x$conf.int)) {
89 ret <- c(ret, conf.low = x$conf.int[1], conf.high = x$conf.int[2])
90 }
91 if (!is.null(x$method)) {
92 ret <- c(ret, method = trimws(as.character(x$method)))
93 }
94 if (!is.null(x$alternative)) {
95 ret <- c(ret, alternative = as.character(x$alternative))
96 }
97
98 # convert matrix columns to vector columns (see GH Issue #1081)
99 dplyr::mutate(as_tibble(ret), dplyr::across(where(is.matrix), c))
100 }
101
102
103 #' @rdname tidy.htest
104 #' @export
105 glance.htest <- function(x, ...) tidy(x)
106
107 #' @templateVar class htest
108 #' @template title_desc_augment
109 #'
110 #' @inherit tidy.htest params examples
111 #'
112 #' @evalRd return_glance(
113 #' .observed = "Observed count.",
114 #' .prop = "Proportion of the total.",
115 #' .row.prop = "Row proportion (2 dimensions table only).",
116 #' .col.prop = "Column proportion (2 dimensions table only).",
117 #' .expected = "Expected count under the null hypothesis.",
118 #' .resid = "Pearson residuals.",
119 #' .std.resid = "Standardized residual."
120 #' )
121 #'
122 #' @details See [stats::chisq.test()] for more details on
123 #' how residuals are computed.
124 #'
125 #' @export
126 #' @seealso [augment()], [stats::chisq.test()]
127 #' @family htest tidiers
128 augment.htest <- function(x, ...) {
129 check_ellipses("newdata", "augment", "htest", ...)
130
131 if (all(c("observed", "expected", "residuals", "stdres") %in% names(x))) {
132 return(augment_chisq_test(x, ...))
133 }
134
135 cli::cli_abort(
136 "{.fn augment.htest} is only defined for chi squared hypothesis tests."
137 )
138 }
139
140 augment_chisq_test <- function(x, ...) {
141 d <- length(dimnames(as.table(x$observed)))
142 ret <- as.data.frame(as.table(x$observed))
143 names(ret)[d + 1] <- ".observed"
144
145 ret <- cbind(
146 ret,
147 .prop = as.data.frame(prop.table(as.table(x$observed)))[[d + 1]]
148 )
149 if (d == 2) {
150 ret <- cbind(
151 ret,
152 .row.prop = as.data.frame(prop.table(as.table(x$observed), 1))[[d + 1]]
153 )
154 ret <- cbind(
155 ret,
156 .col.prop = as.data.frame(prop.table(as.table(x$observed), 2))[[d + 1]]
157 )
158 }
159
160 ret <- cbind(ret, .expected = as.data.frame(as.table(x$expected))[[d + 1]])
161 ret <- cbind(ret, .resid = as.data.frame(as.table(x$residuals))[[d + 1]])
162 ret <- cbind(ret, .std.resid = as.data.frame(as.table(x$stdres))[[d + 1]])
163 as_tibble(ret)
164 }
165
166
167 #' @templateVar class pairwise.htest
168 #' @template title_desc_tidy
169 #'
170 #' @param x A `pairwise.htest` object such as those returned from
171 #' [stats::pairwise.t.test()] or [stats::pairwise.wilcox.test()].
172 #' @template param_unused_dots
173 #'
174 #' @evalRd return_tidy("group1", "group2", "p.value")
175 #'
176 #' @details Note that in one-sided tests, the alternative hypothesis of each
177 #' test can be stated as "group1 is greater/less than group2".
178 #'
179 #' Note also that the columns of group1 and group2 will always be a factor,
180 #' even if the original input is (e.g.) numeric.
181 #'
182 #' @examplesIf rlang::is_installed("modeldata")
183 #'
184 #' attach(airquality)
185 #' Month <- factor(Month, labels = month.abb[5:9])
186 #' ptt <- pairwise.t.test(Ozone, Month)
187 #' tidy(ptt)
188 #'
189 #' library(modeldata)
190 #' data(hpc_data)
191 #' attach(hpc_data)
192 #' ptt2 <- pairwise.t.test(compounds, class)
193 #' tidy(ptt2)
194 #'
195 #' tidy(pairwise.t.test(compounds, class, alternative = "greater"))
196 #' tidy(pairwise.t.test(compounds, class, alternative = "less"))
197 #'
198 #' tidy(pairwise.wilcox.test(compounds, class))
199 #'
200 #' @export
201 #' @seealso [stats::pairwise.t.test()], [stats::pairwise.wilcox.test()],
202 #' [tidy()]
203 #' @family htest tidiers
204 #'
205 tidy.pairwise.htest <- function(x, ...) {
206 tibble(group1 = rownames(x$p.value)) |>
207 cbind(x$p.value) |>
208 pivot_longer(
209 cols = c(dplyr::everything(), -group1),
210 names_to = "group2",
211 values_to = "p.value"
212 ) |>
213 stats::na.omit() |>
214 as_tibble()
215 }
216
217 #' @templateVar class power.htest
218 #' @template title_desc_tidy
219 #'
220 #' @param x A `power.htest` object such as those returned from
221 #' [stats::power.t.test()].
222 #' @template param_unused_dots
223 #'
224 #' @evalRd return_tidy("n", "delta", "sd", "sig.level", "power")
225 #'
226 #' @examplesIf rlang::is_installed("ggplot2")
227 #'
228 #' ptt <- power.t.test(n = 2:30, delta = 1)
229 #' tidy(ptt)
230 #'
231 #' library(ggplot2)
232 #'
233 #' ggplot(tidy(ptt), aes(n, power)) +
234 #' geom_line()
235 #' @export
236 #' @family htest tidiers
237 #' @seealso [stats::power.t.test()]
238 tidy.power.htest <- function(x, ...) {
239 cols <- purrr::compact(x[c(
240 "n",
241 "delta",
242 "sd",
243 "sig.level",
244 "power",
245 "p1",
246 "p2"
247 )])
248 as_tibble(cols)
249 }