Debian Codegraph @

R/lmer.R

raw
1 #-------------------------------------
2 # vcovCR with defaults
3 #-------------------------------------
4
5 #' Cluster-robust variance-covariance matrix for an lmerMod object.
6 #'
7 #' \code{vcovCR} returns a sandwich estimate of the variance-covariance matrix
8 #' of a set of regression coefficient estimates from \code{\link[lme4:merMod-class]{merMod}} object.
9 #'
10 #' @param cluster Optional expression or vector indicating which observations
11 #' belong to the same cluster. If not specified, will be set to
12 #' \code{getGroups(obj)}.
13 #' @param target Optional matrix or vector describing the working
14 #' variance-covariance model used to calculate the \code{CR2} and \code{CR4}
15 #' adjustment matrices. If not specified, the target is taken to be the
16 #' estimated variance-covariance structure of the \code{lmerMod} object.
17 #' @inheritParams vcovCR
18 #'
19 #' @return An object of class \code{c("vcovCR","clubSandwich")}, which consists
20 #' of a matrix of the estimated variance of and covariances between the
21 #' regression coefficient estimates.
22 #'
23 #' @seealso \code{\link{vcovCR}}
24 #'
25 #' @examples
26 #'
27 #' if (requireNamespace("lme4", quietly = TRUE)) {
28 #'
29 #' library(lme4)
30 #' sleep_fit <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
31 #' vcovCR(sleep_fit, type = "CR2")
32 #'
33 #' }
34 #'
35 #' pkgs_available <-
36 #' requireNamespace("lme4", quietly = TRUE) &
37 #' requireNamespace("mlmRev", quietly = TRUE)
38 #'
39 #' if (pkgs_available) {
40 #'
41 #' data(egsingle, package = "mlmRev")
42 #' subset_ids <- levels(egsingle$schoolid)[1:10]
43 #' math_model <- lmer(math ~ year * size + female + black + hispanic
44 #' + (1 | schoolid) + (1 | childid),
45 #' data = egsingle, subset = schoolid %in% subset_ids)
46 #' vcovCR(math_model, type = "CR2")
47 #' }
48 #'
49 #' @export
50
51 vcovCR.lmerMod <- function(obj, cluster, type, target, inverse_var, form = "sandwich", ...) {
52
53 if (!is.null(obj@call$weights)) stop("Models with prior weights are not currently supported.")
54
55 if (missing(cluster)) cluster <- get_outer_group(obj)
56 if(!is_nested_lmerMod(obj, cluster)) stop("Non-nested random effects detected. clubSandwich methods are not available for such models.")
57
58 if (missing(target)) target <- NULL
59 if (missing(inverse_var)) inverse_var <- is.null(target)
60
61 vcov_CR(obj, cluster = cluster, type = type,
62 target = target, inverse_var = inverse_var, form = form)
63 }
64
65 #-------------------------------------
66 # check nesting of random effects
67 #-------------------------------------
68
69 get_outer_group <- function(obj) {
70 group_n <- lme4::getME(obj, "l_i")
71 group_facs <- lme4::getME(obj, "flist")
72 group_facs[[which.min(group_n)]]
73 }
74
75 check_nested <- function(inner_grp, outer_grp) {
76 n_outer <- tapply(outer_grp, inner_grp, function(x) length(unique(x)))
77 all(n_outer == 1)
78 }
79
80 is_nested_lmerMod <- function(obj, cluster = get_outer_group(obj)) {
81 group_facs <- lme4::getME(obj, "flist")
82 nested <- vapply(group_facs, check_nested, outer_grp = cluster, FUN.VALUE = TRUE)
83 all(nested)
84 }
85
86
87 # nobs()
88 #-------------------------------------
89 # model_matrix()
90 #-------------------------------------
91
92 #' @export
93
94 model_matrix.lmerMod <- function(obj) {
95 model_matrix <- model.matrix(obj)
96 }
97
98 #-------------------------------------
99 # coef_CS()
100 #-------------------------------------
101
102 #' @export
103
104 coef_CS.lmerMod <- function(obj)
105 lme4::getME(obj, "fixef")
106
107 #-------------------------------------
108 # residuals_CS()
109 #-------------------------------------
110
111 #' @export
112
113 residuals_CS.lmerMod <- function(obj) {
114 y <- lme4::getME(obj, "y")
115 X <- lme4::getME(obj, "X")
116 beta <- lme4::getME(obj, "fixef")
117 y - as.numeric(X %*% beta)
118 }
119
120
121 #-------------------------------------
122 # Get (model-based) working variance matrix
123 #-------------------------------------
124
125 #' @export
126
127 targetVariance.lmerMod <- function(obj, cluster = get_outer_group(obj)) {
128
129 Z_mat <- lme4::getME(obj, "Z")
130 Lambdat <- lme4::getME(obj, "Lambdat")
131 Zlam_list <- matrix_list(Matrix::tcrossprod(Z_mat, Lambdat), fac = cluster, dim = "row")
132 target_list <- lapply(Zlam_list, function(z) Matrix::tcrossprod(z) + Matrix::Diagonal(n = NROW(z)))
133
134 lapply(target_list, as.matrix)
135 }
136
137 #-------------------------------------
138 # Get weighting matrix
139 #-------------------------------------
140
141 #' @export
142
143 weightMatrix.lmerMod <- function(obj, cluster = get_outer_group(obj)) {
144 V_list <- targetVariance(obj, cluster)
145 lapply(V_list, function(v) chol2inv(chol(v)))
146
147 }
148
149 #---------------------------------------
150 # Get bread matrix and scaling constant
151 #---------------------------------------
152
153 #' @export
154
155 bread.lmerMod <- function(x, ...) {
156 sigma_sq <- lme4::getME(x, "sigma")^2
157 as.matrix(vcov(x) * v_scale(x)) / sigma_sq
158 }
159
160 #' @export
161
162 v_scale.lmerMod <- function(obj) {
163 min(lme4::getME(obj, "l_i"))
164 }