Debian Codegraph @

R/stats-glm.R

raw
1 #' @templateVar class glm
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `glm` object returned from [stats::glm()].
5 #' @template param_confint
6 #' @template param_exponentiate
7 #' @template param_unused_dots
8 #'
9 #' @export
10 #' @family lm tidiers
11 #' @seealso [stats::glm()]
12 tidy.glm <- function(
13 x,
14 conf.int = FALSE,
15 conf.level = .95,
16 exponentiate = FALSE,
17 ...
18 ) {
19 warn_on_appropriated_glm_class(x)
20 warn_on_subclass(x, "tidy")
21
22 ret <- as_tibble(summary(x)$coefficients, rownames = "term")
23 colnames(ret) <- c("term", "estimate", "std.error", "statistic", "p.value")
24
25 coefs <- stats::coef(x)
26
27 if (length(coefs) != nrow(ret)) {
28 # summary(x)$coefficients misses rank deficient rows (i.e. coefs that
29 # summary.lm() sets to NA), catch them here and add them back. This join is
30 # costly, so only do it when necessary.
31 coefs <- tibble::enframe(coefs, name = "term", value = "estimate")
32 ret <- left_join(coefs, ret, by = c("term", "estimate"))
33 }
34
35 if (conf.int) {
36 ci <- broom_confint_terms(x, level = conf.level)
37 ret <- dplyr::left_join(ret, ci, by = "term")
38 }
39
40 if (exponentiate) {
41 ret <- exponentiate(ret)
42 }
43
44 ret
45 }
46
47 #' @templateVar class glm
48 #' @template title_desc_augment
49 #'
50 #' @param x A `glm` object returned from [stats::glm()].
51 #' @template param_data
52 #' @template param_newdata
53 #' @param type.predict Passed to [stats::predict.glm()] `type`
54 #' argument. Defaults to `"link"`.
55 #' @param type.residuals Passed to [stats::residuals.glm()] and
56 #' to [stats::rstandard.glm()] `type` arguments. Defaults to `"deviance"`.
57 #' @template param_se_fit
58 #' @template param_unused_dots
59 #'
60 #' @evalRd return_augment(
61 #' ".se.fit",
62 #' ".hat",
63 #' ".sigma",
64 #' ".std.resid",
65 #' ".cooksd"
66 #' )
67 #'
68 #' @details If the weights for any of the observations in the model
69 #' are 0, then columns ".infl" and ".hat" in the result will be 0
70 #' for those observations.
71 #'
72 #' A `.resid` column is not calculated when data is specified via
73 #' the `newdata` argument.
74 #'
75 #' @export
76 #' @family lm tidiers
77 #' @seealso [stats::glm()]
78 #' @include stats-lm.R
79 augment.glm <- function(
80 x,
81 data = model.frame(x),
82 newdata = NULL,
83 type.predict = c("link", "response", "terms"),
84 type.residuals = c("deviance", "pearson"),
85 se_fit = FALSE,
86 ...
87 ) {
88 warn_on_appropriated_glm_class(x)
89 warn_on_subclass(x, "augment")
90
91 type.predict <- rlang::arg_match(type.predict)
92 type.residuals <- rlang::arg_match(type.residuals)
93
94 df <- if (is.null(newdata)) data else newdata
95 df <- as_augment_tibble(df)
96
97 # don't use augment_newdata here; don't want raw/response residuals in .resid
98 if (se_fit) {
99 pred_obj <- predict(x, newdata, type = type.predict, se.fit = TRUE)
100 df$.fitted <- pred_obj$fit |> unname()
101 df$.se.fit <- pred_obj$se.fit |> unname()
102 } else {
103 if (is.null(newdata)) {
104 df$.fitted <- predict(x, type = type.predict) |> unname()
105 } else {
106 df$.fitted <- predict(x, newdata, type = type.predict) |> unname()
107 }
108 }
109
110 if (is.null(newdata)) {
111 tryCatch(
112 {
113 infl <- influence(x, do.coef = FALSE)
114 df$.resid <- residuals(x, type = type.residuals) |> unname()
115 df <- add_hat_sigma_cols(df, x, infl)
116 df$.std.resid <- rstandard(x, infl = infl, type = type.residuals) |>
117 unname()
118 df$.cooksd <- cooks.distance(x, infl = infl) |> unname()
119 },
120 error = data_error
121 )
122 }
123
124 df
125 }
126
127
128 #' @templateVar class glm
129 #' @template title_desc_glance
130 #'
131 #' @param x A `glm` object returned from [stats::glm()].
132 #' @template param_unused_dots
133 #'
134 #' @evalRd return_glance(
135 #' "null.deviance",
136 #' "df.null",
137 #' "logLik",
138 #' "AIC",
139 #' "BIC",
140 #' "deviance",
141 #' "df.residual",
142 #' "nobs"
143 #' )
144 #'
145 #' @examples
146 #'
147 #' g <- glm(am ~ mpg, mtcars, family = "binomial")
148 #' glance(g)
149 #' @export
150 #' @family lm tidiers
151 #' @seealso [stats::glm()]
152 glance.glm <- function(x, ...) {
153 warn_on_appropriated_glm_class(x)
154 warn_on_subclass(x, "glance")
155
156 as_glance_tibble(
157 null.deviance = x$null.deviance,
158 df.null = x$df.null,
159 logLik = as.numeric(stats::logLik(x)),
160 AIC = stats::AIC(x),
161 BIC = stats::BIC(x),
162 deviance = stats::deviance(x),
163 df.residual = stats::df.residual(x),
164 nobs = stats::nobs(x),
165 na_types = "rirrrrii"
166 )
167 }
168
169 warn_on_appropriated_glm_class <- function(x, call = caller_env()) {
170 warn_on_glm2(x)
171 warn_on_stanreg(x, call = call)
172
173 invisible(TRUE)
174 }
175
176 # the output of glm2::glm2 has the same class as objects outputted
177 # by stats::glm2. glm2 outputs are currently not supported (intentionally)
178 # so warn that output is not maintained.
179 warn_on_glm2 <- function(x) {
180 if (!is.null(x$method) & is.character(x$method)) {
181 if (x$method == "glm.fit2") {
182 cli::cli_warn(
183 c(
184 "{.arg x} seems to be outputted from the {.pkg glm2} package.",
185 "i" = "Tidiers for {.pkg glm2} output are currently not maintained;
186 please use caution in interpreting {.pkg broom} output."
187 ),
188 call = NULL
189 )
190 }
191 }
192
193 invisible(TRUE)
194 }
195
196 # stanreg objects subclass glm, glm tidiers error out (uninformatively),
197 # and the maintained stanreg tidiers live in broom.mixed.
198 warn_on_stanreg <- function(x, call = caller_env()) {
199 if (!is.null(x$stan_function)) {
200 cli::cli_abort(
201 c(
202 "{.arg x} seems to be outputted from the {.pkg rstanarm} package.",
203 "i" = "Tidiers for mixed model output now live in {.pkg broom.mixed}."
204 ),
205 call = call
206 )
207 }
208
209 invisible(TRUE)
210 }