Debian Codegraph @

R/mmrm.R

raw
1 # Default methods work for mmrm objects:
2 # model_matrix.default() — model.matrix(obj) works; weights are all positive
3 # residuals_CS.default() — residuals(obj) works; weights are all positive
4 # coef_CS.default() — coef(obj) works directly
5
6 #-------------------------------------
7 # vcovCR with defaults
8 #-------------------------------------
9
10 #' Cluster-robust variance-covariance matrix for an mmrm object.
11 #'
12 #' \code{vcovCR} returns a sandwich estimate of the variance-covariance matrix
13 #' of a set of regression coefficient estimates from an
14 #' \code{\link[mmrm]{mmrm}} object.
15 #'
16 #' @param cluster Optional expression or vector indicating which observations
17 #' belong to the same cluster. If not specified, will be set to the subject
18 #' variable from the \code{mmrm} model formula.
19 #' @param target Optional matrix or vector describing the working
20 #' variance-covariance model used to calculate the \code{CR2} and \code{CR4}
21 #' adjustment matrices. If not specified, the target is taken to be the
22 #' estimated variance-covariance structure of the \code{mmrm} object, with
23 #' weights applied if present.
24 #' @inheritParams vcovCR
25 #'
26 #' @return An object of class \code{c("vcovCR","clubSandwich")}, which consists
27 #' of a matrix of the estimated variance of and covariances between the
28 #' regression coefficient estimates.
29 #'
30 #' @seealso \code{\link{vcovCR}}
31 #'
32 #' @examples
33 #'
34 #' if (requireNamespace("mmrm", quietly = TRUE)) withAutoprint({
35 #'
36 #' library(mmrm)
37 #' data(fev_data, package = "mmrm")
38 #'
39 #' # Fit an mmrm model with unstructured covariance
40 #' mmrm_fit <- mmrm(
41 #' FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
42 #' data = fev_data
43 #' )
44 #'
45 #' # CR2 cluster-robust variance estimator (cluster auto-detected)
46 #' vcovCR(mmrm_fit, type = "CR2")
47 #'
48 #' # Coefficient tests with Satterthwaite degrees of freedom
49 #' coef_test(mmrm_fit, vcov = "CR2", test = "Satterthwaite")
50 #'
51 #' # Fit a weighted mmrm model
52 #' fev_data$wt <- 1 + rpois(nrow(fev_data), lambda = 3)
53 #' mmrm_wt <- mmrm(
54 #' FEV1 ~ RACE + SEX + ARMCD + us(AVISIT | USUBJID),
55 #' data = fev_data,
56 #' weights = fev_data$wt
57 #' )
58 #'
59 #' # CR2 works with weighted models
60 #' vcovCR(mmrm_wt, type = "CR2")
61 #'
62 #' })
63 #'
64 #' @export
65
66 vcovCR.mmrm <- function(obj, cluster, type, target, inverse_var, form = "sandwich", ...) {
67 if (missing(cluster)) {
68 ff <- mmrm::component(obj, "full_frame")
69 subject_var <- mmrm::component(obj, "subject_var")
70 cluster <- droplevels(as.factor(ff[[subject_var]]))
71 }
72 if (missing(target)) target <- NULL
73 if (missing(inverse_var)) inverse_var <- is.null(target)
74 vcov_CR(obj, cluster = cluster, type = type,
75 target = target, inverse_var = inverse_var, form = form)
76 }
77
78 #-------------------------------------
79 # targetVariance()
80 #-------------------------------------
81
82 #' @export
83
84 targetVariance.mmrm <- function(obj, cluster) {
85 ff <- mmrm::component(obj, "full_frame")
86 visit_var <- obj$formula_parts$visit_var
87 group_var <- obj$formula_parts$group_var
88 visit_levels <- levels(ff[[visit_var]])
89 visits <- ff[[visit_var]]
90 vc <- mmrm::VarCorr(obj)
91
92 obs_by_subject <- split(seq_along(cluster), cluster)
93
94 if (is.null(group_var)) {
95 # Non-grouped: single covariance matrix for all subjects
96 V_list <- lapply(obs_by_subject, function(rows) {
97 idx <- match(as.character(visits[rows]), visit_levels)
98 unname(vc[idx, idx, drop = FALSE])
99 })
100 } else {
101 # Grouped: pick the group-specific covariance matrix per subject
102 groups <- ff[[group_var]]
103 V_list <- lapply(obs_by_subject, function(rows) {
104 subj_group <- as.character(groups[rows[1]])
105 idx <- match(as.character(visits[rows]), visit_levels)
106 unname(vc[[subj_group]][idx, idx, drop = FALSE])
107 })
108 }
109
110 # Multiply by weights if non-unit
111 wts <- ff[["(weights)"]]
112
113 if (all(wts == 1)) {
114 return(V_list)
115 } else {
116 wt_inv_sqrt_j <- split(1 / sqrt(wts), cluster)
117 V_weighted <- Map(function(iw, V) tcrossprod(iw) * V, iw = wt_inv_sqrt_j, V = V_list)
118 return(V_weighted)
119 }
120 }
121
122 #-------------------------------------
123 # weightMatrix()
124 #-------------------------------------
125
126 #' @export
127
128 weightMatrix.mmrm <- function(obj, cluster) {
129 V_list <- targetVariance(obj, cluster)
130 lapply(V_list, function(v) chol2inv(chol(v)))
131 }
132
133 #---------------------------------------
134 # bread and scaling constant
135 #---------------------------------------
136
137 #' @export
138
139 bread.mmrm <- function(x, ...) {
140 vcov(x) * v_scale(x)
141 }
142
143 #' @export
144
145 v_scale.mmrm <- function(obj) {
146 mmrm::component(obj, "n_subjects")
147 }
148