Debian Codegraph @

R/geeglm.R

raw
1 #-------------------------------------
2 # vcovCR with defaults
3 #-------------------------------------
4
5 #' Cluster-robust variance-covariance matrix for a geeglm object.
6 #'
7 #' \code{vcovCR} returns a sandwich estimate of the variance-covariance matrix
8 #' of a set of regression coefficient estimates from an \code{\link[geepack]{geeglm}} object.
9 #'
10 #' @param cluster Expression or vector indicating which observations belong to
11 #' the same cluster. Required for \code{geeglm} objects.
12 #' @param target Optional matrix or vector describing the working
13 #' variance-covariance model used to calculate the \code{CR2} and \code{CR4}
14 #' adjustment matrices. If a vector, the target matrix is assumed to be
15 #' diagonal. If not specified, the target is taken to be the estimated variance function.
16 #' @inheritParams vcovCR
17 #'
18 #' @return An object of class \code{c("vcovCR","clubSandwich")}, which consists
19 #' of a matrix of the estimated variance of and covariances between the
20 #' regression coefficient estimates.
21 #'
22 #' @seealso \code{\link{vcovCR}}
23 #'
24 #' @examples
25 #'
26 #' if (requireNamespace("geepack", quietly = TRUE)) {
27 #'
28 #' library(geepack)
29 #' data(dietox, package = "geepack")
30 #' dietox$Cu <- as.factor(dietox$Cu)
31 #' mf <- formula(Weight ~ Cu * (Time + I(Time^2) + I(Time^3)))
32 #' gee1 <- geeglm(mf, data=dietox, id=Pig, family=poisson("identity"), corstr="ar1")
33 #' V_CR <- vcovCR(gee1, cluster = dietox$Pig, type = "CR2")
34 #' coef_test(gee1, vcov = V_CR, test = "Satterthwaite")
35 #'
36 #' }
37 #'
38 #' @export
39
40 vcovCR.geeglm <- function(obj, cluster, type, target = NULL, inverse_var = NULL, form = "sandwich", ...) {
41 if (missing(cluster)) {
42 cluster <- as.factor(obj$id)
43 names(cluster) <- NULL
44 }
45 if (is.null(inverse_var)) inverse_var <- is.null(target)
46 vcov_CR(obj, cluster = cluster, type = type,
47 target = target, inverse_var = inverse_var, form = form)
48 }
49
50 # coef()
51 # nobs()
52
53 #-----------------------------------------------
54 # Model matrix
55 #-----------------------------------------------
56
57 #' @export
58
59 model_matrix.geeglm <- function(obj) {
60 X <- model.matrix(obj)
61 eta <- obj$linear.predictors
62 dmu_deta <- obj$family$mu.eta
63 d <- as.vector(dmu_deta(eta))
64 d * X
65 }
66
67 #-------------------------------------
68 # residuals
69 #-------------------------------------
70
71 #' @export
72
73 residuals_CS.geeglm <- function(obj) {
74 residuals(obj, type = "response")
75 }
76
77 #-----------------------------------------------
78 # Get (model-based) working variance matrix
79 #-----------------------------------------------
80
81 ar1_cor <- function(n, alpha) {
82 exponent <- abs(matrix(1:n - 1, nrow = n, ncol = n, byrow = TRUE) -
83 (1:n - 1))
84 alpha^exponent
85 }
86
87 get_dist <- function(v) {
88 mat_dist <- as.matrix(dist(v, diag = TRUE, upper = TRUE))
89 mat_dist
90 }
91
92 other_cor <- function(alpha, n = (1 + sqrt(1 + 4 * 2 * length(alpha))) / 2) {
93 x <- matrix(1, nrow = n, ncol = n)
94 x[lower.tri(x)] <- alpha
95 x[upper.tri(x)] <- t(x)[upper.tri(x)]
96 x
97 }
98
99 #' @export
100
101 targetVariance.geeglm <- function(obj, cluster) {
102
103 idvar <- as.factor(obj$id)
104 mu <- fitted.values(obj)
105 var_fun <- obj$family$variance
106 v <- as.numeric(var_fun(mu))
107 w <- weights(obj, type = "prior")
108 a <- tapply(v / w, idvar, sqrt)
109 aa <- lapply(a, tcrossprod)
110
111 if (obj$corstr %in% c("independence", "exchangeable", "ar1", "unstructured", "userdefined", "fixed") == F) {
112 stop("Working correlation matrix must be a matrix with the following correlation structures: independence, exchangeable, ar1, unstructured, or userdefined")
113 } else if (obj$corstr == "ar1") {
114 if (is.null(obj$call$waves)) {
115 r <- lapply(obj$geese$clusz, ar1_cor, alpha = obj$geese$alpha)
116 } else {
117 wave <- eval(obj$call$waves, envir = obj$data)
118 wave_vec <- split(wave, ceiling(seq_along(wave) / obj$geese$clusz))
119 exponent <- lapply(wave_vec, get_dist)
120 get_str <- function(alpha, exponent) {
121 alpha_str <- alpha^exponent
122 alpha_str
123 }
124 r <- lapply(exponent, get_str, alpha = obj$geese$alpha)
125 }
126 } else if (obj$corstr == "unstructured") {
127 r <- lapply(obj$geese$clusz, other_cor, alpha = as.numeric(obj$geese$alpha))
128 } else if (obj$corstr %in% c("userdefined","fixed")) {
129
130 formula_env <- attr(obj$formula, ".Environment")
131 if (as.character(obj$call$zcor) %in% objects(formula_env)) {
132 zcor <- eval(obj$call$zcor, envir = formula_env)
133 } else {
134 zcor <- eval(obj$call$zcor, envir = parent.frame())
135 }
136
137 id_cor <- table(idvar)
138 id_cor <- rep(names(id_cor), id_cor * (id_cor - 1) / 2)
139
140 if (obj$corstr == "userdefined") {
141 alpha <- as.numeric(obj$geese$alpha)
142 r_vec <- as.numeric(zcor %*% alpha)
143 r <- tapply(r_vec, id_cor, other_cor)
144 } else if (obj$corstr == "fixed") {
145 r <- tapply(zcor, id_cor, other_cor)
146 }
147 }
148
149 v <- mapply("*", aa, r, SIMPLIFY = FALSE)
150 v <- nest_bdiag(v, crosswalk = data.frame(idvar, as.factor(cluster)))
151 v
152 }
153
154 #####################
155 #-------------------------------------
156 # Get weighting matrix
157 #-------------------------------------
158
159 ar1_cor_inv <- function(n, alpha) {
160 if (n == 1) {
161 matrix(1)
162 } else {
163 r_inv <- diag(c(1,rep(1 + alpha^2, n - 2), 1), nrow = n)
164 index <- cbind(2:n, 1:(n-1))
165 r_inv[index] <- r_inv[index[,2:1]] <- -alpha
166 r_inv
167 }
168 }
169
170 exch_inv <- function(n, alpha) {
171 diag(1 / (1 - alpha), nrow = n) - alpha / ((1 - alpha) * (alpha * (n - 1) + 1))
172 }
173
174 #' @export
175
176 weightMatrix.geeglm <- function(obj, cluster) {
177
178 idvar <- as.factor(obj$id)
179
180 if (obj$corstr %in% c("independence", "exchangeable", "ar1", "unstructured", "userdefined", "fixed") == F) {
181 stop("Working correlation matrix must be a matrix with the following correlation structures: independence, exchangeable, ar1, unstructured, or userdefined")
182 } else if (obj$corstr %in% c("unstructured","userdefined", "fixed")) {
183
184 # Invert the targetVariance for unstructured or user-defined working models
185 V_list <- targetVariance.geeglm(obj, idvar)
186 W_list <- lapply(V_list, function(v) chol2inv(chol(v)))
187
188 } else {
189
190 # Otherwise use analytic formulas for inverse of targetVariance
191
192 mu <- fitted.values(obj)
193 var_fun <- obj$family$variance
194 v <- as.numeric(var_fun(mu))
195 w <- weights(obj, type = "prior")
196
197 if (obj$corstr %in% c("exchangeable","ar1")) {
198 a <- tapply(w / v, idvar, sqrt)
199 aa <- lapply(a, tcrossprod)
200
201 if (obj$corstr == "ar1") {
202
203 if (is.null(obj$call$waves)) {
204 r_inv <- lapply(obj$geese$clusz, ar1_cor_inv, alpha = obj$geese$alpha)
205 } else {
206 wave <- eval(obj$call$waves, envir = obj$data)
207 wave_vec <- split(wave, ceiling(seq_along(wave) / obj$geese$clusz))
208 exponent <- lapply(wave_vec, get_dist)
209 get_str <- function(alpha, exponent) {
210 alpha_str <- alpha^exponent
211 alpha_str
212 }
213 r <- lapply(exponent, get_str, alpha = obj$geese$alpha)
214 r_inv <- lapply(r, function(x) chol2inv(chol(x)))
215 }
216 } else if (obj$corstr == "exchangeable") {
217 r_inv <- lapply(obj$geese$clusz, exch_inv, alpha = obj$geese$alpha)
218 }
219
220 W_list <- mapply("*", aa, r_inv, SIMPLIFY = FALSE)
221
222 } else {
223 W_list <- matrix_list(w / v, idvar, dim = "both")
224 }
225 }
226
227 W_list <- nest_bdiag(W_list, crosswalk = data.frame(idvar, as.factor(cluster)))
228
229 return(W_list)
230
231 }
232
233 #---------------------------------------
234 # Get bread matrix and scaling constant
235 #---------------------------------------
236
237 #' @export
238
239 bread.geeglm <- function(x, ...) {
240 cluster <- droplevels(as.factor(x$id))
241 X <- model_matrix(x)
242 X_list <- matrix_list(X, cluster, "row")
243 W_list <- weightMatrix(x, cluster)
244 XWX <- Reduce("+", Map(function(x, w) t(x) %*% w %*% x, x = X_list, w = W_list))
245 M <- chol2inv(chol(XWX / v_scale(x)))
246 rownames(M) <- colnames(M) <- colnames(X)
247 M
248 }
249
250 #' @export
251
252 v_scale.geeglm <- function(obj) {
253 if (substr(obj$family$family, 1, 17) %in% c("poisson", "binomial", "Negative Binomial")) {
254 dispersion <- 1
255 } else {
256 wres <- as.vector(residuals(obj, "working")) * weights(obj, "working")
257 dispersion <- sum(wres^2)/sum(weights(obj, "working"))
258 }
259 as.vector(sum(summary(obj)$df[1:2])) * dispersion
260 }
261