Debian Codegraph @

R/metafor.R

raw
1 #' @templateVar class rma
2 #' @template title_desc_tidy
3 #'
4 #' @param x An `rma` object such as those created by [metafor::rma()],
5 #' [metafor::rma.uni()], [metafor::rma.glmm()], [metafor::rma.mh()],
6 #' [metafor::rma.mv()], or [metafor::rma.peto()].
7 #' @template param_confint
8 #' @template param_exponentiate
9 #' @param include_studies Logical. Should individual studies be included in the
10 #' output? Defaults to `FALSE`.
11 #' @template param_unused_dots
12 #' @param measure Measure type. See [metafor::escalc()]
13 #'
14 #' @evalRd return_tidy(
15 #' term = "The name of the individual study",
16 #' type = "The estimate type (summary vs individual study)",
17 #' "estimate",
18 #' "std.error",
19 #' "statistic",
20 #' "p.value",
21 #' "conf.low",
22 #' "conf.high"
23 #' )
24 #' @export
25 #'
26 #' @examplesIf rlang::is_installed("metafor")
27 #'
28 #' # load libraries for models and data
29 #' library(metafor)
30 #'
31 #' df <-
32 #' escalc(
33 #' measure = "RR",
34 #' ai = tpos,
35 #' bi = tneg,
36 #' ci = cpos,
37 #' di = cneg,
38 #' data = dat.bcg
39 #' )
40 #'
41 #' meta_analysis <- rma(yi, vi, data = df, method = "EB")
42 #'
43 #' tidy(meta_analysis)
44 #'
45 #' @rdname metafor_tidiers
46 #'
47 tidy.rma <- function(
48 x,
49 conf.int = FALSE,
50 conf.level = 0.95,
51 exponentiate = FALSE,
52 include_studies = FALSE,
53 measure = "GEN",
54 ...
55 ) {
56 # tidy summary estimates
57 betas <- x$beta
58 if (!is.null(nrow(betas)) && nrow(betas) > 1) {
59 # get estimate type and fix spelling
60 study <- rownames(betas)
61 swap <- grepl("intrcpt", study)
62 study[swap] <- "intercept"
63 betas <- as.double(betas)
64 } else {
65 study <- "overall"
66 betas <- betas[1]
67 }
68
69 if (x$level != 1 - conf.level) {
70 level <- 1 - conf.level
71 if (is.element(x$test, c("knha", "adhoc", "t"))) {
72 crit <- if (all(x$ddf > 0))
73 qt(level / 2, df = x$ddf, lower.tail = FALSE) else NA
74 } else {
75 crit <- qnorm(level / 2, lower.tail = FALSE)
76 }
77 conf.low <- c(betas - crit * x$se)
78 conf.high <- c(betas + crit * x$se)
79 } else {
80 conf.low <- x$ci.lb
81 conf.high <- x$ci.ub
82 }
83
84 results <- tibble::tibble(
85 term = study,
86 type = "summary",
87 estimate = betas,
88 std.error = x$se,
89 statistic = x$zval,
90 p.value = x$pval,
91 conf.low = conf.low,
92 conf.high = conf.high
93 )
94
95 # tidy individual studies
96 if (include_studies) {
97 # use `metafor::escalc` to standardize estimates and confidence intervals
98 estimates <- metafor::escalc(
99 yi = x$yi.f,
100 vi = x$vi.f,
101 measure = measure
102 ) |>
103 summary(level = conf.level * 100) |>
104 as.data.frame(stringsAsFactors = FALSE)
105
106 n_studies <- length(x$slab)
107
108 estimates <- dplyr::bind_cols(
109 term = as.character(x$slab),
110 # dplyr::bind_cols is strict about recycling, so repeat for each study
111 type = rep("study", n_studies),
112 estimates[, c("yi", "sei", "zi")],
113 p.value = rep(NA, n_studies),
114 estimates[, c("ci.lb", "ci.ub")]
115 )
116
117 names(estimates) <- c(
118 "term",
119 "type",
120 "estimate",
121 "std.error",
122 "statistic",
123 "p.value",
124 "conf.low",
125 "conf.high"
126 )
127 estimates <- as_tibble(estimates)
128 results <- dplyr::bind_rows(estimates, results)
129 }
130
131 if (exponentiate) {
132 results <- exponentiate(results)
133 }
134
135 if (!conf.int) {
136 results <- dplyr::select(results, -conf.low, -conf.high)
137 }
138
139 results
140 }
141
142 #' @templateVar class rma
143 #' @template title_desc_glance
144 #'
145 #' @inheritParams tidy.rma
146 #'
147 #' @evalRd return_glance(
148 #' "nobs",
149 #' "measure",
150 #' "method",
151 #' "i.squared",
152 #' "h.squared",
153 #' "tau.squared",
154 #' "tau.squared.se",
155 #' "cochran.qe",
156 #' "p.value.cochran.qe",
157 #' "cochran.qm",
158 #' "p.value.cochran.qm",
159 #' "df.residual"
160 #' )
161 #' @export
162 #'
163 #' @examplesIf rlang::is_installed("metafor")
164 #'
165 #' library(metafor)
166 #'
167 #' df <-
168 #' escalc(
169 #' measure = "RR",
170 #' ai = tpos,
171 #' bi = tneg,
172 #' ci = cpos,
173 #' di = cneg,
174 #' data = dat.bcg
175 #' )
176 #'
177 #' meta_analysis <- rma(yi, vi, data = df, method = "EB")
178 #'
179 #' glance(meta_analysis)
180 #'
181 glance.rma <- function(x, ...) {
182 # reshape model fit statistics and clean names
183 fit_stats <- metafor::fitstats(x)
184 fit_stats <- fit_stats |>
185 t() |>
186 as.data.frame()
187 names(fit_stats) <-
188 stringr::str_replace(names(fit_stats), "\\:", "")
189
190 # metafor returns different fit statistics for different models
191 # so use a list + `purrr::discard` to remove unrelated / missing statistics
192
193 results <- list(
194 i.squared = x$I2,
195 h.squared = x$H2,
196 tau.squared = x$tau2,
197 tau.squared.se = x$se.tau2,
198 cochran.qe = x$QE,
199 p.value.cochran.qe = x$QEp,
200 cochran.qm = x$QM,
201 p.value.cochran.qm = x$QMp,
202 df.residual = df.residual(x)
203 ) |>
204 purrr::discard(is.null) |>
205 purrr::discard(purrr::is_empty) |>
206 # drop multivariate statistics
207 purrr::discard(~ length(.x) >= 2) |>
208 as_tibble()
209
210 if (!purrr::is_empty(fit_stats) && nrow(fit_stats) == 1) {
211 results <- dplyr::bind_cols(results, fit_stats)
212 }
213
214 results$nobs <- x$k
215
216 results
217 }
218
219 #' @templateVar class rma
220 #' @template title_desc_augment
221 #'
222 #' @inheritParams tidy.rma
223 #' @param interval For `rma.mv` models, should prediction intervals
224 #' (`"prediction"`, default) or confidence intervals (`"confidence"`)
225 #' intervals be returned? For `rma.uni` models, prediction intervals are
226 #' always returned. For `rma.mh` and `rma.peto` models, confidence intervals
227 #' are always returned.
228 #'
229 #' @evalRd return_augment(
230 #' .observed = "The observed values for the individual studies",
231 #' ".fitted",
232 #' ".se.fit",
233 #' ".lower",
234 #' ".upper",
235 #' ".resid",
236 #' ".moderator",
237 #' ".moderator.level"
238 #' )
239 #'
240 #' @export
241 #'
242 #' @examplesIf rlang::is_installed("metafor")
243 #'
244 #' # load modeling library
245 #' library(metafor)
246 #'
247 #' # generate data and fit
248 #' df <-
249 #' escalc(
250 #' measure = "RR",
251 #' ai = tpos,
252 #' bi = tneg,
253 #' ci = cpos,
254 #' di = cneg,
255 #' data = dat.bcg
256 #' )
257 #'
258 #' meta_analysis <- rma(yi, vi, data = df, method = "EB")
259 #'
260 #' # summarize model fit with tidiers
261 #' augment(meta_analysis)
262 #'
263 augment.rma <- function(x, interval = c("prediction", "confidence"), ...) {
264 check_ellipses("newdata", "augment", "rma", ...)
265
266 # metafor generally handles these for different models through the monolith
267 # `rma` class; using `purrr::possibly` primarily helps discard unused
268 # components but also helps get the right component for each model
269 blup0 <- purrr::possibly(metafor::blup, NULL)
270 residuals0 <- purrr::possibly(stats::residuals, NULL)
271 influence0 <- purrr::possibly(stats::influence, NULL)
272
273 y <- x$yi.f
274 # get best linear unbiased predictors if available
275 pred <- blup0(x)
276 # otherwise use `predict.rma()`
277 if (is.null(pred)) pred <- predict(x)
278 pred <- as.data.frame(pred)
279
280 # fix names
281 interval <- match.arg(interval, c("prediction", "confidence"))
282 if (
283 interval == "prediction" &
284 any(names(pred) %in% c("cr.lb", "cr.ub", "pi.lb", "pi.ub"))
285 ) {
286 confidence_intervals <- names(pred) %in% c("ci.lb", "ci.ub")
287 pred <- pred[, !confidence_intervals]
288 names(pred)[1:4] <- c(".fitted", ".se.fit", ".lower", ".upper")
289 } else {
290 prediction_intervals <- names(pred) %in%
291 c("cr.lb", "cr.ub", "pi.lb", "pi.ub")
292 pred <- pred[, !prediction_intervals]
293 names(pred)[1:4] <- c(".fitted", ".se.fit", ".lower", ".upper")
294 }
295 moderator <- names(pred) == "X"
296 names(pred)[moderator] <- ".moderator"
297 moderator_level <- names(pred) == "tau2.level"
298 names(pred)[moderator_level] <- ".moderator.level"
299
300 res <- residuals0(x)
301 inf <- influence0(x)
302 # if model has influence statistics, bind them and clean their names
303 if (!is.null(inf)) {
304 inf <- dplyr::bind_cols(as.data.frame(inf$inf), dfbetas = inf$dfbs$intrcpt)
305 inf <- dplyr::select(
306 inf,
307 .hat = hat,
308 .cooksd = cook.d,
309 .std.resid = rstudent,
310 .dffits = dffits,
311 .cov.ratio = cov.r,
312 .tau.squared.loo = tau2.del,
313 .cochran.qe.loo = QE.del,
314 .weight = weight,
315 .dfbetas = dfbetas
316 )
317 }
318
319 if (nrow(pred) == 1) {
320 # Some metafor models only return a single prediction
321 # based on the summary estimate. `dplyr::bind_cols()` requires
322 # `pred` to be the same length as other results, so replicate
323 # prediction for each row
324 pred <- purrr::map_dfr(seq_along(x$slab), ~pred)
325 }
326
327 ret <- dplyr::bind_cols(
328 .rownames = as.character(x$slab),
329 .observed = y,
330 pred
331 )
332
333 # join residuals, if they exist for the model
334 if (!is.null(res)) {
335 res <- tibble::enframe(res, name = ".rownames", value = ".resid")
336 ret <- dplyr::left_join(ret, res, by = ".rownames")
337 }
338
339 # don't return rownames if they are just row numbers
340 no_study_names <- all(x$slab == as.character(seq_along(x$slab)))
341 if (no_study_names) ret$.rownames <- NULL
342
343 ret <- ret |> dplyr::select(-dplyr::contains("cr."))
344
345 tibble::as_tibble(ret)
346 }