Debian Codegraph @

R/rma-mv.R

raw
1
2 #----------------------------------------------------------------------
3 # utility function for computing block-diagonal covariance matrices
4 #----------------------------------------------------------------------
5
6 isPosDef <- function(x) {
7 x_na <- is.na(x)
8 mis_rows <- apply(x_na, 1, all)
9 mis_cols <- apply(x_na, 2, all)
10 if (all(mis_rows) | all(mis_cols)) return(TRUE)
11 x_nomiss <- x[!mis_rows, !mis_cols]
12 x_eig <- eigen(x_nomiss)
13 all(x_eig$values > 0)
14 }
15
16 check_PD <- function(vcov_list) {
17 PD <- sapply(vcov_list, isPosDef)
18 if (!all(PD)) {
19 NPD_clusters <- names(vcov_list)[!PD]
20 warn_text <- paste(c("The following clusters have non-positive definite covariance matrices:", NPD_clusters), collapse = "\n")
21 warning(warn_text)
22 } else {
23 NULL
24 }
25 }
26
27 #' Impute a block-diagonal covariance matrix
28 #'
29 #' @description `r lifecycle::badge("superseded")`
30 #'
31 #' This function is superseded by the \code{\link[metafor]{vcalc}} provided by
32 #' the \code{metafor} package. Compared to \code{impute_covariance_matrix},
33 #' \code{\link[metafor]{vcalc}} provides many further features, includes a
34 #' \code{data} argument, and uses syntax that is consistent with other
35 #' functions in \code{metafor}.
36 #'
37 #' \code{impute_covariance_matrix} calculates a block-diagonal covariance
38 #' matrix, given the marginal variances, the block structure, and an assumed
39 #' correlation structure. Can be used to create compound-symmetric structures,
40 #' AR(1) auto-correlated structures, or combinations thereof.
41 #'
42 #' @param vi Vector of variances
43 #' @param cluster Vector indicating which effects belong to the same cluster.
44 #' Effects with the same value of `cluster` will be treated as correlated.
45 #' @param r Vector or numeric value of assumed constant correlation(s) between
46 #' effect size estimates from each study.
47 #' @param ti Vector of time-points describing temporal spacing of effects, for
48 #' use with auto-regressive correlation structures.
49 #' @param ar1 Vector or numeric value of assumed AR(1) auto-correlation(s)
50 #' between effect size estimates from each study. If specified, then \code{ti}
51 #' argument must be specified.
52 #' @param smooth_vi Logical indicating whether to smooth the marginal variances
53 #' by taking the average \code{vi} within each cluster. Defaults to
54 #' \code{FALSE}.
55 #' @param subgroup Vector of category labels describing sub-groups of effects.
56 #' If non-null, effects that share the same category label and the same
57 #' cluster will be treated as correlated, but effects with different category
58 #' labels will be treated as uncorrelated, even if they come from the same
59 #' cluster.
60 #' @param return_list Optional logical indicating whether to return a list of
61 #' matrices (with one entry per block) or the full variance-covariance matrix.
62 #' @param check_PD Optional logical indicating whether to check whether each
63 #' covariance matrix is positive definite. If \code{TRUE} (the default), the
64 #' function will display a warning if any covariance matrix is not positive
65 #' definite.
66 #'
67 #'
68 #'
69 #' @return If \code{cluster} is appropriately sorted, then a list of matrices,
70 #' with one entry per cluster, will be returned by default. If \code{cluster}
71 #' is out of order, then the full variance-covariance matrix will be returned
72 #' by default. The output structure can be controlled with the optional
73 #' \code{return_list} argument.
74 #'
75 #' @details A block-diagonal variance-covariance matrix (possibly represented as
76 #' a list of matrices) with a specified structure. The structure depends on
77 #' whether the \code{r} argument, \code{ar1} argument, or both arguments are
78 #' specified. Let \eqn{v_{ij}}{v-ij} denote the specified variance for effect
79 #' \eqn{i}{i} in cluster \eqn{j}{j} and \eqn{C_{hij}}{C-hij} be the covariance
80 #' between effects \eqn{h}{h} and \eqn{i}{i} in cluster
81 #' \eqn{j}{j}.
82 #' \itemize{
83 #' \item{If only \code{r} is specified, each block of the variance-covariance
84 #' matrix will have a constant (compound symmetric) correlation, so that
85 #' \deqn{C_{hij} = r_j \sqrt{v_{hj} v_{ij},}}{C-hij = r-j * sqrt(v-hj v-ij),}
86 #' where \eqn{r_j}{r-j} is the specified correlation
87 #' for cluster \eqn{j}{j}. If only a single value is given in \code{r}, then
88 #' it will be used for every cluster.}
89 #' \item{If only \code{ar1} is specified, each block of the variance-covariance matrix will have an
90 #' AR(1) auto-correlation structure, so that
91 #' \deqn{C_{hij} = \phi_j^{|t_{hj}- t_{ij}|} \sqrt{v_{hj} v_{ij},}}{C-hij = (ar1-j)^|t-hj - t-ij| * sqrt(v-hj v-ij),}
92 #' where \eqn{\phi_j}{ar1-j} is the specified auto-correlation
93 #' for cluster \eqn{j}{j} and \eqn{t_{hj}}{t-hj} and \eqn{t_{ij}}{t-ij}
94 #' are specified time-points corresponding to effects \eqn{h}{h} and
95 #' \eqn{i}{i} in cluster \eqn{j}{j}. If only a single value is given in
96 #' \code{ar1}, then it will be used for every cluster.}
97 #' \item{If both \code{r} and \code{ar1} are specified, each block of the variance-covariance matrix will have combination of compound symmetric and an AR(1)
98 #' auto-correlation structures, so that
99 #' \deqn{C_{hij} = \left[r_j + (1 - r_j)\phi_j^{|t_{hj} - t_{ij}|}\right] \sqrt{v_{hj} v_{ij},}}{C-hij = [r-j + (1 - r-j)(ar1-j)^|t-hj - t-ij|] * sqrt(v-hj v-ij),}
100 #' where \eqn{r_j}{r-j} is the specified constant correlation for cluster
101 #' \eqn{j}{j}, \eqn{\phi_j}{ar1-j} is the specified auto-correlation for
102 #' cluster \eqn{j}{j} and \eqn{t_{hj}}{t-hj} and \eqn{t_{ij}}{t-ij} are
103 #' specified time-points corresponding to effects \eqn{h}{h} and
104 #' \eqn{i}{i} in cluster \eqn{j}{j}. If only single values are given in
105 #' \code{r} or \code{ar1}, they will be used for every cluster.}
106 #' }
107 #' If \code{smooth_vi = TRUE}, then all of the variances within cluster
108 #' \eqn{j}{j} will be set equal to the average variance of cluster
109 #' \eqn{j}{j}, i.e., \deqn{v'_{ij} = \frac{1}{n_j} \sum_{i=1}^{n_j}
110 #' v_{ij}}{v-ij' = (v-1j + ... + v-nj,j) / n-j} for
111 #' \eqn{i=1,...,n_j}{i=1,...,n-j} and \eqn{j=1,...,k}{j=1,...,k}.
112 #'
113 #' @export
114 #'
115 #' @examples
116 #'
117 #' if (requireNamespace("metafor", quietly = TRUE)) {
118 #'
119 #' library(metafor)
120 #'
121 #' # Constant correlation
122 #' data(SATcoaching)
123 #' V_list <- impute_covariance_matrix(vi = SATcoaching$V, cluster = SATcoaching$study, r = 0.66)
124 #' MVFE <- rma.mv(d ~ 0 + test, V = V_list, data = SATcoaching)
125 #' conf_int(MVFE, vcov = "CR2", cluster = SATcoaching$study)
126 #'
127 #' }
128 #'
129
130
131 impute_covariance_matrix <- function(vi, cluster, r, ti, ar1,
132 smooth_vi = FALSE,
133 subgroup = NULL,
134 return_list = identical(as.factor(cluster), sort(as.factor(cluster))),
135 check_PD = TRUE) {
136
137 lifecycle::deprecate_soft("0.5.11", "impute_covariance_matrix()", "metafor::vcalc()")
138
139 cluster <- droplevels(as.factor(cluster))
140
141 vi_list <- split(vi, cluster)
142
143 if (smooth_vi) vi_list <- lapply(vi_list, function(x) rep(mean(x, na.rm = TRUE), length(x)))
144
145 if (missing(r) & missing(ar1)) stop("You must specify a value for r or for ar1.")
146
147 if (!missing(r)) {
148 r_list <- rep_len(r, length(vi_list))
149 if (missing(ar1)) {
150 vcov_list <- Map(function(V, rho) (rho + diag(1 - rho, nrow = length(V))) * tcrossprod(sqrt(V)),
151 V = vi_list,
152 rho = r_list)
153 }
154 }
155
156 if (!missing(ar1)) {
157 if (missing(ti)) stop("If you specify a value for ar1, you must provide a vector for ti.")
158
159 ti_list <- split(ti, cluster)
160 ar_list <- rep_len(ar1, length(vi_list))
161
162 if (missing(r)) {
163 vcov_list <- Map(function(V, time, phi) (phi^as.matrix(stats::dist(time))) * tcrossprod(sqrt(V)),
164 V = vi_list,
165 time = ti_list,
166 phi = ar_list)
167 } else {
168 vcov_list <- Map(function(V, rho, time, phi) (rho + (1 - rho) * phi^as.matrix(stats::dist(time))) * tcrossprod(sqrt(V)),
169 V = vi_list,
170 rho = r_list,
171 time = ti_list,
172 phi = ar_list)
173 }
174
175 vcov_list <- lapply(vcov_list, function(x) {
176 attr(x, "dimnames") <- NULL
177 x
178 })
179 }
180
181 if (!is.null(subgroup)) {
182 si_list <- split(subgroup, cluster)
183 subgroup_list <- lapply(si_list, function(x) sapply(x, function(y) y == x))
184 vcov_list <- Map(function(V, S) V * S, V = vcov_list, S = subgroup_list)
185 }
186
187 if (check_PD) check_PD(vcov_list)
188
189 if (return_list) {
190 return(vcov_list)
191 } else {
192 vcov_mat <- unblock(vcov_list)
193 cluster_index <- order(order(cluster))
194 return(vcov_mat[cluster_index, cluster_index])
195 }
196 }
197
198
199 #' Impute a patterned block-diagonal covariance matrix
200 #'
201 #' @description `r lifecycle::badge("superseded")`
202 #'
203 #' This function is superseded by the \code{\link[metafor]{vcalc}} provided by
204 #' the \code{metafor} package. Compared to \code{pattern_covariance_matrix},
205 #' \code{\link[metafor]{vcalc}} provides many further features, includes a
206 #' \code{data} argument, and uses syntax that is consistent with other
207 #' functions in \code{metafor}.
208 #'
209 #' @description \code{pattern_covariance_matrix} calculates a
210 #' block-diagonal covariance matrix, given the marginal variances, the block
211 #' structure, and an assumed correlation structure defined by a patterned
212 #' correlation matrix.
213 #'
214 #' @param vi Vector of variances
215 #' @param cluster Vector indicating which effects belong to the same cluster.
216 #' Effects with the same value of `cluster` will be treated as correlated.
217 #' @param pattern_level Vector of categories for each effect size, used to
218 #' determine which entry of the pattern matrix will be used to impute a
219 #' correlation.
220 #' @param r_pattern Patterned correlation matrix with row and column names
221 #' corresponding to the levels of \code{pattern}.
222 #' @inheritParams impute_covariance_matrix
223 #'
224 #' @return If \code{cluster} is appropriately sorted, then a list of matrices,
225 #' with one entry per cluster, will be returned by default. If \code{cluster}
226 #' is out of order, then the full variance-covariance matrix will be returned
227 #' by default. The output structure can be controlled with the optional
228 #' \code{return_list} argument.
229 #'
230 #' @details A block-diagonal variance-covariance matrix (possibly represented as
231 #' a list of matrices) with a specified correlation structure, defined by a
232 #' patterned correlation matrix. Let \eqn{v_{ij}}{v-ij} denote the specified
233 #' variance for effect \eqn{i}{i} in cluster \eqn{j}{j} and
234 #' \eqn{C_{hij}}{C-hij} be the covariance between effects \eqn{h}{h} and
235 #' \eqn{i}{i} in cluster \eqn{j}{j}. Let \eqn{p_{ij}}{p-ij} be the level
236 #' of the pattern variable for effect \eqn{i}{i} in cluster \eqn{j}{j},
237 #' taking a value in \eqn{1,...,C}{1,...,C}. A patterned correlation matrix
238 #' is defined as a set of correlations between pairs of effects taking each
239 #' possible combination of patterns. Formally, let \eqn{r_{cd}}{r-cd} be the
240 #' correlation between effects in categories \eqn{c}{c} and \eqn{d}{d},
241 #' respectively, where \eqn{r_{cd} = r_{dc}}{r-cd = r-dc}. Then the
242 #' covariance between effects \eqn{h}{h} and \eqn{i}{i} in cluster
243 #' \eqn{j}{j} is taken to be \deqn{C_{hij} = \sqrt{v_{hj} v_{ij}} \times
244 #' r_{p_{hj} p_{ij}}.}{C-hij = sqrt(v-hj v-ij) * r[p-hj, p-ij].}
245 #'
246 #' Correlations between effect sizes within the same category are defined by the diagonal
247 #' values of the pattern matrix, which may take values less than one.
248 #'
249 #' Combinations of pattern levels that do not occur in the patterned correlation matrix will be set equal to \code{r}.
250 #'
251 #' If \code{smooth_vi = TRUE}, then all of the variances within cluster
252 #' \eqn{j}{j} will be set equal to the average variance of cluster
253 #' \eqn{j}{j}, i.e., \deqn{v'_{ij} = \frac{1}{n_j} \sum_{i=1}^{n_j}
254 #' v_{ij}}{v-ij' = (v-1j + ... + v-nj,j) / n-j} for
255 #' \eqn{i=1,...,n_j}{i=1,...,n-j} and \eqn{j=1,...,k}{j=1,...,k}.
256 #'
257 #' @export
258 #'
259 #' @examples
260 #'
261 #' pkgs_available <-
262 #' requireNamespace("metafor", quietly = TRUE) &
263 #' requireNamespace("robumeta", quietly = TRUE)
264 #'
265 #' if (pkgs_available) {
266 #' library(metafor)
267 #'
268 #' data(oswald2013, package = "robumeta")
269 #' dat <- escalc(data = oswald2013, measure = "ZCOR", ri = R, ni = N)
270 #' subset_ids <- unique(dat$Study)[1:20]
271 #' dat <- subset(dat, Study %in% subset_ids)
272 #'
273 #' # make a patterned correlation matrix
274 #'
275 #' p_levels <- levels(dat$Crit.Cat)
276 #' r_pattern <- 0.7^as.matrix(dist(1:length(p_levels)))
277 #' diag(r_pattern) <- seq(0.75, 0.95, length.out = 6)
278 #' rownames(r_pattern) <- colnames(r_pattern) <- p_levels
279 #'
280 #' # impute the covariance matrix using patterned correlations
281 #' V_list <- pattern_covariance_matrix(vi = dat$vi,
282 #' cluster = dat$Study,
283 #' pattern_level = dat$Crit.Cat,
284 #' r_pattern = r_pattern,
285 #' smooth_vi = TRUE)
286 #'
287 #' # fit a model using imputed covariance matrix
288 #'
289 #' MVFE <- rma.mv(yi ~ 0 + Crit.Cat, V = V_list,
290 #' random = ~ Crit.Cat | Study,
291 #' data = dat)
292 #'
293 #' conf_int(MVFE, vcov = "CR2")
294 #'
295 #' }
296 #'
297
298
299 pattern_covariance_matrix <- function(vi, cluster, pattern_level, r_pattern, r,
300 smooth_vi = FALSE, subgroup = NULL,
301 return_list = identical(as.factor(cluster), sort(as.factor(cluster))),
302 check_PD = TRUE) {
303
304 lifecycle::deprecate_soft("0.5.11", "impute_covariance_matrix()", "metafor::vcalc()")
305
306 if (missing(pattern_level)) stop("You must specify a vector for pattern_level.")
307 if (any(is.na(pattern_level[!is.na(vi)]))) stop("The pattern_level vector cannot have missing values.")
308
309 pattern_level <- as.factor(pattern_level)
310
311 if (!identical(rownames(r_pattern),colnames(r_pattern))) stop("Row names of r_pattern must be identical to column names.")
312
313 mat_levels <- rownames(r_pattern)
314 p_levels <- levels(pattern_level)
315
316 if (!all(p_levels %in% mat_levels)) {
317
318 if (missing(r)) stop("At least one pattern_level is not available in r_pattern. Please specify a value for the r argument.")
319
320 np_levels <- nlevels(pattern_level)
321 r_pattern_full <- matrix(r, nrow = np_levels, ncol = np_levels)
322 rownames(r_pattern_full) <- colnames(r_pattern_full) <- p_levels
323 included_levels <- intersect(mat_levels, p_levels)
324 r_pattern_full[included_levels, included_levels] <- r_pattern[included_levels, included_levels]
325 r_pattern <- r_pattern_full
326 }
327
328
329 cluster <- droplevels(as.factor(cluster))
330
331 pattern_list <- split(pattern_level, cluster)
332
333 cor_list <- lapply(pattern_list, function(x) {
334 res <- r_pattern[x, x, drop=FALSE]
335 diag(res) <- 1
336 res
337 })
338
339 vi_list <- split(vi, cluster)
340
341 if (smooth_vi) vi_list <- lapply(vi_list, function(x) rep(mean(x, na.rm = TRUE), length(x)))
342
343 vcov_list <- Map(function(V, r_mat) r_mat * tcrossprod(sqrt(V)),
344 V = vi_list,
345 r_mat = cor_list)
346
347
348 if (!is.null(subgroup)) {
349 si_list <- split(subgroup, cluster)
350 subgroup_list <- lapply(si_list, function(x) sapply(x, function(y) y == x))
351 vcov_list <- Map(function(V, S) V * S, V = vcov_list, S = subgroup_list)
352 }
353
354 if (check_PD) check_PD(vcov_list)
355
356 if (return_list) {
357 return(vcov_list)
358 } else {
359 vcov_mat <- unblock(vcov_list)
360 cluster_index <- order(order(cluster))
361 return(vcov_mat[cluster_index, cluster_index])
362 }
363 }
364
365 #-------------------------------------
366 # vcovCR with defaults
367 #-------------------------------------
368
369 #' Cluster-robust variance-covariance matrix for a rma.mv object.
370 #'
371 #' \code{vcovCR} returns a sandwich estimate of the variance-covariance matrix
372 #' of a set of regression coefficient estimates from a
373 #' \code{\link[metafor]{rma.mv}} object.
374 #'
375 #' @param cluster Optional expression or vector indicating which observations
376 #' belong to the same cluster. If not specified, will be set to the factor in
377 #' the random-effects structure with the fewest distinct levels. Caveat
378 #' emptor: the function does not check that the random effects are nested.
379 #' @param target Optional matrix or vector describing the working
380 #' variance-covariance model used to calculate the \code{CR2} and \code{CR4}
381 #' adjustment matrices. If not specified, the target is taken to be the
382 #' estimated variance-covariance structure of the \code{rma.mv} object.
383 #' @inheritParams vcovCR
384 #'
385 #' @return An object of class \code{c("vcovCR","clubSandwich")}, which consists
386 #' of a matrix of the estimated variance of and covariances between the
387 #' regression coefficient estimates.
388 #'
389 #' @seealso \code{\link{vcovCR}}
390 #'
391 #' @export
392 #'
393 #' @examples
394 #'
395 #' pkgs_available <-
396 #' requireNamespace("metafor", quietly = TRUE) &
397 #' requireNamespace("metadat", quietly = TRUE)
398 #'
399 #' if (pkgs_available) withAutoprint({
400 #'
401 #' library(metafor)
402 #' data(dat.assink2016, package = "metadat")
403 #'
404 #' mfor_fit <- rma.mv(yi ~ year + deltype,
405 #' V = vi, random = ~ 1 | study / esid,
406 #' data = dat.assink2016)
407 #' mfor_fit
408 #'
409 #' mfor_CR2 <- vcovCR(mfor_fit, type = "CR2")
410 #' mfor_CR2
411 #'
412 #' coef_test(mfor_fit, vcov = mfor_CR2, test = c("Satterthwaite", "saddlepoint"))
413 #' Wald_test(mfor_fit, constraints = constrain_zero(3:4), vcov = mfor_CR2)
414 #'
415 #' })
416 #'
417
418 vcovCR.rma.mv <- function(obj, cluster, type, target, inverse_var, form = "sandwich", ...) {
419
420 if (obj$withR) stop("vcovCR.rma.mv() does not work with fixed correlation matrices in the R argument.")
421
422 if (missing(cluster)) {
423 cluster <- findCluster.rma.mv(obj)
424 } else {
425 # check that random effects are nested within clustering variable
426 mod_struct <- parse_structure(obj)
427
428 if (length(cluster) != NROW(mod_struct$cluster_dat)) {
429 cluster <- cluster[obj$not.na]
430 }
431
432 nested <- test_nested(cluster, fac = mod_struct$cluster_dat)
433 if (!all(nested)) stop("Random effects are not nested within clustering variable.")
434 }
435
436 if (missing(target)) {
437 target <- NULL
438 inverse_var <- is.null(obj$W)
439 } else {
440 if (missing(inverse_var)) inverse_var <- FALSE
441 }
442 vcov_CR(obj, cluster = cluster, type = type,
443 target = target, inverse_var = inverse_var, form = form)
444 }
445
446 # coef()
447 # residuals_CS()
448 # vcov()
449 # model_matrix
450
451 #-------------------------------------
452 # Get (model-based) working variance matrix
453 #-------------------------------------
454
455 #' @export
456
457 targetVariance.rma.mv <- function(obj, cluster) {
458 tV <- matrix_list(obj$M, cluster, "both")
459 if (!all(sapply(tV, is.matrix))) tV <- lapply(tV, as.matrix)
460 return(tV)
461 }
462
463 #-------------------------------------
464 # Get weighting matrix
465 #-------------------------------------
466
467 #' @export
468
469 weightMatrix.rma.mv <- function(obj, cluster) {
470 if (is.null(obj$W)) {
471 V_list <- targetVariance(obj, cluster)
472 Wm <- lapply(V_list, function(v) chol2inv(chol(v)))
473 } else{
474 Wm <- matrix_list(obj$W, cluster, "both")
475 if (!all(sapply(Wm, is.matrix))) Wm <- lapply(Wm, as.matrix)
476 }
477 return(Wm)
478 }
479
480 #-----------------------------------------------
481 # Get outer-most clustering variable
482 #-----------------------------------------------
483
484 get_structure <- function(obj) {
485 data.frame(G = obj$withG, H = obj$withH, R = obj$withR, S = obj$withS)
486 }
487
488 test_nested <- function(cluster, fac) {
489
490 if (is.list(fac)) {
491 res <- sapply(fac, test_nested, cluster = cluster)
492 return(res)
493 }
494
495 groupings <- tapply(cluster, fac, function(x) length(unique(x)))
496 all(groupings==1L)
497 }
498
499 nest_structure <- function(x) {
500
501 if (length(x) == 1) return(x)
502
503 y <- x
504 for (i in 2:length(x)) {
505 names(y)[i] <- paste(names(x)[1:i], collapse = "/")
506 y[i] <- do.call(paste, c(x[1:i], sep = "/"))
507 }
508
509 y
510 }
511
512 parse_structure <- function(obj) {
513
514 level_dat <- vector(mode = "integer")
515 cluster_dat <- data.frame(row.names = 1:obj$k)
516
517 if (obj$withG) {
518 level_dat[["G"]] <- obj$g.nlevels[[2]]
519 cluster_dat$G <- obj$mf.g$outer
520 }
521
522 if (obj$withH) {
523 level_dat[["H"]] <- obj$h.nlevels[[2]]
524 cluster_dat$H <- obj$mf.h$outer
525 }
526
527 if (obj$withS) {
528 s_levels <- obj$s.nlevels
529 names(s_levels) <- obj$s.names
530 level_dat <- c(level_dat, s_levels)
531
532 mf_r <- lapply(obj$mf.r, nest_structure)
533 mf_all <- do.call(cbind, mf_r)
534 mf_s <- mf_all[obj$s.names]
535 cluster_dat <- cbind(cluster_dat, mf_s)
536 cluster_dat <- droplevels(cluster_dat)
537 }
538
539 list(level_dat = level_dat, cluster_dat = cluster_dat)
540 }
541
542 #' Detect cluster structure of an rma.mv object
543 #'
544 #' \code{findCluster.rma.mv} returns a vector of ID variables for the highest level of clustering in a fitted \code{rma.mv} model.
545 #'
546 #' @param obj A fitted \code{rma.mv} object.
547 #'
548 #' @return A a vector of ID variables for the highest level of clustering in \code{obj}.
549 #'
550 #' @export
551 #'
552 #' @examples
553 #'
554 #' if (requireNamespace("metafor", quietly = TRUE)) {
555 #'
556 #' library(metafor)
557 #' data(dat.assink2016, package = "metadat")
558 #'
559 #' mfor_fit <- rma.mv(yi ~ year + deltype,
560 #' V = vi, random = ~ 1 | study / esid,
561 #' data = dat.assink2016)
562 #'
563 #' findCluster.rma.mv(mfor_fit)
564 #'
565 #' }
566 #'
567
568 findCluster.rma.mv <- function(obj) {
569
570 if (!inherits(obj, "rma.mv")) stop("`obj` must be a fitted rma.mv model.")
571
572 if (obj$withR) stop("vcovCR.rma.mv() does not work with fixed correlation matrices in the R argument.")
573
574 # parse model structure
575 mod_struct <- parse_structure(obj)
576
577 if (length(mod_struct$level_dat) == 0L) stop("No clustering variable specified.")
578
579 # determine cluster with smallest number of levels
580
581 highest_cluster <- names(mod_struct$level_dat)[which.min(mod_struct$level_dat)]
582 cluster <- mod_struct$cluster_dat[[highest_cluster]]
583
584 # check that random effects are nested within clustering variable
585 nested <- test_nested(cluster, fac = mod_struct$cluster_dat)
586 if (!all(nested)) stop("Random effects are not nested within clustering")
587
588 # clean up
589 if (!is.factor(cluster)) cluster <- as.factor(cluster)
590 droplevels(cluster)
591 }
592
593 #---------------------------------------
594 # Get bread matrix and scaling constant
595 #---------------------------------------
596
597 #' @export
598
599 bread.rma.mv <- function(x, ...) {
600
601 if (inherits(x, "robust.rma")) {
602 cluster <- findCluster.rma.mv(x)
603 W <- weightMatrix(x, cluster = cluster)
604 X_mat <- model_matrix(x)
605 X_list <- matrix_list(X_mat, fac = cluster, dim = "row")
606 XWX_list <- Map(function(x, w) t(x) %*% w %*% x, x = X_list, w = W)
607 XWX <- Reduce(`+`, XWX_list)
608 } else {
609 if (is.null(x$W)) {
610 s2w <- if (is.null(x$s2w)) 1 else x$s2w
611 B <- nobs(x) * vcov(x) / s2w
612 return(B)
613 } else {
614 X_mat <- model_matrix(x)
615 XWX <- t(X_mat) %*% x$W %*% X_mat
616 }
617 }
618 B <- chol2inv(chol(XWX)) * nobs(x)
619 rownames(B) <- colnames(B) <- colnames(X_mat)
620 return(B)
621 }
622
623 #' @export
624
625 v_scale.rma.mv <- function(obj) {
626 nobs(obj)
627 }