Debian Codegraph @

R/quantreg-rq.R

raw
1 #' @templateVar class rq
2 #' @template title_desc_tidy
3 #'
4 #' @param x An `rq` object returned from [quantreg::rq()].
5 #' @param se.type Character specifying the method to use to calculate
6 #' standard errors. Passed to [quantreg::summary.rq()] `se` argument.
7 #' Defaults to `"rank"` if the sample size is less than 1000,
8 #' otherwise defaults to `"nid"`.
9 #' @template param_confint
10 #' @param ... Additional arguments passed to [quantreg::summary.rq()].
11 #'
12 #' @details If `se.type = "rank"` confidence intervals are calculated by
13 #' `summary.rq` and `statistic` and `p.value` values are not returned.
14 #' When only a single predictor is included in the model,
15 #' no confidence intervals are calculated and the confidence limits are
16 #' set to NA.
17 #'
18 #' @evalRd return_tidy(regression = TRUE)
19 #'
20 #' @aliases rq_tidiers quantreg_tidiers
21 #' @export
22 #' @seealso [tidy()], [quantreg::rq()]
23 #' @family quantreg tidiers
24 #'
25 #' @examplesIf rlang::is_installed("quantreg")
26 #'
27 #' # load modeling library and data
28 #' library(quantreg)
29 #'
30 #' data(stackloss)
31 #'
32 #' # median (l1) regression fit for the stackloss data.
33 #' mod1 <- rq(stack.loss ~ stack.x, .5)
34 #'
35 #' # weighted sample median
36 #' mod2 <- rq(rnorm(50) ~ 1, weights = runif(50))
37 #'
38 #' # summarize model fit with tidiers
39 #' tidy(mod1)
40 #' glance(mod1)
41 #' augment(mod1)
42 #'
43 #' tidy(mod2)
44 #' glance(mod2)
45 #' augment(mod2)
46 #'
47 #' # varying tau to generate an rqs object
48 #' mod3 <- rq(stack.loss ~ stack.x, tau = c(.25, .5))
49 #'
50 #' tidy(mod3)
51 #' augment(mod3)
52 #'
53 #' # glance cannot handle rqs objects like `mod3`--use a purrr
54 #' # `map`-based workflow instead
55 #'
56 tidy.rq <- function(
57 x,
58 se.type = NULL,
59 conf.int = FALSE,
60 conf.level = 0.95,
61 ...
62 ) {
63 check_ellipses("exponentiate", "tidy", "rq", ...)
64
65 # specification for confidence level inverted for summary.rq
66 alpha <- 1 - conf.level
67
68 # se.type default contingent on sample size
69 n <- length(x$residuals)
70 if (is.null(se.type)) {
71 se.type <- if (n < 1001) "rank" else "nid"
72 }
73
74 # summary.rq often issues warnings when computing standard error
75 rq_summary <- suppressWarnings(
76 quantreg::summary.rq(x, se = se.type, alpha = alpha, ...)
77 )
78
79 process_rq(
80 rq_obj = rq_summary,
81 se.type = se.type,
82 conf.int = conf.int,
83 conf.level = conf.level
84 )
85 }
86
87 #' @templateVar class rq
88 #' @template title_desc_glance
89 #'
90 #' @inherit tidy.rq examples params
91 #' @template param_unused_dots
92 #'
93 #' @evalRd return_glance(
94 #' "tau",
95 #' "logLik",
96 #' "AIC",
97 #' "BIC",
98 #' "df.residual"
99 #' )
100 #'
101 #' @details Only models with a single `tau` value may be passed.
102 #' For multiple values, please use a [purrr::map()] workflow instead, e.g.
103 #' ```
104 #' taus |>
105 #' map(function(tau_val) rq(y ~ x, tau = tau_val)) |>
106 #' map_dfr(glance)
107 #' ```
108 #'
109 #' @export
110 #' @seealso [glance()], [quantreg::rq()]
111 #' @family quantreg tidiers
112 glance.rq <- function(x, ...) {
113 n <- length(fitted(x))
114 s <- summary(x)
115
116 as_glance_tibble(
117 tau = x[["tau"]],
118 logLik = logLik(x),
119 AIC = AIC(x),
120 BIC = AIC(x, k = log(n)),
121 df.residual = rep(s[["rdf"]], times = length(x[["tau"]])),
122 na_types = "rrrri"
123 )
124 }
125
126 #' @templateVar class rq
127 #' @template title_desc_augment
128 #'
129 #' @param x An `rq` object returned from [quantreg::rq()].
130 #' @template param_data
131 #' @template param_newdata
132 #' @inheritDotParams quantreg::predict.rq
133 #'
134 #' @inherit tidy.rq examples
135 #'
136 #' @evalRd return_augment(".tau")
137 #'
138 #' @details Depending on the arguments passed on to `predict.rq` via `...`,
139 #' a confidence interval is also calculated on the fitted values resulting in
140 #' columns `.lower` and `.upper`. Does not provide confidence
141 #' intervals when data is specified via the `newdata` argument.
142 #'
143 #' @export
144 #' @seealso [augment], [quantreg::rq()], [quantreg::predict.rq()]
145 #' @family quantreg tidiers
146 augment.rq <- function(x, data = model.frame(x), newdata = NULL, ...) {
147 args <- list(...)
148 force_newdata <- FALSE
149 if ("interval" %in% names(args) && args[["interval"]] != "none") {
150 force_newdata <- TRUE
151 }
152 if (is.null(newdata)) {
153 original <- data
154 original[[".resid"]] <- residuals(x)
155 if (force_newdata) {
156 pred <- predict(x, newdata = data, ...)
157 } else {
158 pred <- predict(x, ...)
159 }
160 } else {
161 original <- newdata
162 pred <- predict(x, newdata = newdata, ...)
163 }
164
165 if (NCOL(pred) == 1) {
166 original[[".fitted"]] <- pred
167 original[[".tau"]] <- x[["tau"]]
168 return(as_tibble(original))
169 } else {
170 colnames(pred) <- c(".fitted", ".lower", ".upper")
171 original[[".tau"]] <- x[["tau"]]
172 return(as_tibble(cbind(original, pred)))
173 }
174 }
175
176 process_rq <- function(
177 rq_obj,
178 se.type = NULL,
179 conf.int = TRUE,
180 conf.level = 0.95
181 ) {
182 nn <- c("estimate", "std.error", "statistic", "p.value")
183 co <- as.data.frame(rq_obj[["coefficients"]])
184 if (se.type == "rank") {
185 # if only a single predictor is included, confidence interval not calculated
186 # set to NA to preserve dimensions of object
187 if (1 == ncol(co)) {
188 co <- cbind(co, NA, NA)
189 }
190 co <- setNames(co, c("estimate", "conf.low", "conf.high"))
191 conf.int <- FALSE
192 } else {
193 co <- setNames(co, nn)
194 }
195 if (conf.int) {
196 a <- (1 - conf.level) / 2
197 cv <- qt(c(a, 1 - a), df = rq_obj[["rdf"]])
198 co[["conf.low"]] <- co[["estimate"]] + (cv[1] * co[["std.error"]])
199 co[["conf.high"]] <- co[["estimate"]] + (cv[2] * co[["std.error"]])
200 }
201 co[["tau"]] <- rq_obj[["tau"]]
202 as_tidy_tibble(co)
203 }