| 1 |
#------------------------------------- |
| 2 |
# vcovCR with defaults |
| 3 |
#------------------------------------- |
| 4 |
|
| 5 |
#' Cluster-robust variance-covariance matrix for an |
| 6 |
#' \code{estimatr::iv_robust} object. |
| 7 |
#' |
| 8 |
#' \code{vcovCR} returns a sandwich estimate of the variance-covariance matrix |
| 9 |
#' of a set of regression coefficient estimates from an |
| 10 |
#' \code{\link[estimatr]{iv_robust}} object. |
| 11 |
#' |
| 12 |
#' @param cluster Vector indicating which observations belong to |
| 13 |
#' the same cluster. Required for \code{iv_robust} objects unless the model |
| 14 |
#' was fitted with a \code{clusters} argument. |
| 15 |
#' @param target Optional matrix or vector describing the working |
| 16 |
#' variance-covariance model used to calculate the \code{CR2} and \code{CR4} |
| 17 |
#' adjustment matrices. If a vector, the target matrix is assumed to be |
| 18 |
#' diagonal. If not specified, the target is taken to be an identity matrix. |
| 19 |
#' @param inverse_var Not used for \code{iv_robust} objects. |
| 20 |
#' @inheritParams vcovCR |
| 21 |
#' |
| 22 |
#' @return An object of class \code{c("vcovCR","clubSandwich")}, which consists |
| 23 |
#' of a matrix of the estimated variance of and covariances between the |
| 24 |
#' regression coefficient estimates. |
| 25 |
#' |
| 26 |
#' @seealso \code{\link{vcovCR}} |
| 27 |
#' |
| 28 |
#' @examples |
| 29 |
#' |
| 30 |
#' if (requireNamespace("estimatr", quietly = TRUE)) withAutoprint({ |
| 31 |
#' library(estimatr) |
| 32 |
#' |
| 33 |
#' set.seed(20261201) |
| 34 |
#' N <- 200 |
| 35 |
#' cluster <- factor(rep(1:20, each = 10)) |
| 36 |
#' z1 <- rnorm(N) |
| 37 |
#' z2 <- rnorm(N) |
| 38 |
#' x_exog <- rnorm(N) |
| 39 |
#' x_endog <- 0.5 * z1 + 0.3 * z2 + rnorm(N) |
| 40 |
#' y <- 1 + 2 * x_endog + 0.5 * x_exog + rnorm(N) |
| 41 |
#' dat <- data.frame(y, x_endog, x_exog, z1, z2, cluster) |
| 42 |
#' |
| 43 |
#' # Basic 2SLS with clusters and CR2 |
| 44 |
#' iv_fit <- iv_robust( |
| 45 |
#' y ~ x_endog + x_exog | x_exog + z1 + z2, |
| 46 |
#' data = dat, |
| 47 |
#' clusters = cluster, se_type = "CR2" |
| 48 |
#' ) |
| 49 |
#' vcovCR(iv_fit) |
| 50 |
#' conf_int(iv_fit, vcov = "CR2") |
| 51 |
#' |
| 52 |
#' # 2SLS with fixed effects |
| 53 |
#' iv_fe <- iv_robust( |
| 54 |
#' y ~ x_endog + x_exog | x_exog + z1 + z2, |
| 55 |
#' fixed_effects = ~ cluster, |
| 56 |
#' data = dat, |
| 57 |
#' clusters = cluster, |
| 58 |
#' se_type = "CR2" |
| 59 |
#' ) |
| 60 |
#' vcovCR(iv_fe) |
| 61 |
#' conf_int(iv_fe, vcov = "CR2") |
| 62 |
#' }) |
| 63 |
#' |
| 64 |
#' @export |
| 65 |
|
| 66 |
vcovCR.iv_robust <- function(obj, cluster, type, target = NULL, inverse_var = FALSE, form = "sandwich", ...) { |
| 67 |
|
| 68 |
if (inverse_var != FALSE) stop("The inverse_var option is not available for iv_robust models.") |
| 69 |
|
| 70 |
if (isTRUE(obj$fes) && !requireNamespace("fixest", quietly = TRUE)) { |
| 71 |
message("For improved performance in models with fixed effects, install the {fixest} package.") |
| 72 |
} |
| 73 |
|
| 74 |
obj$model.frame <- model.frame(obj) |
| 75 |
|
| 76 |
if (missing(cluster)) { |
| 77 |
cluster <- findCluster.iv_robust(obj) |
| 78 |
if (is.null(cluster)) stop("You must specify a clustering variable or `obj` must include a clustering variable.") |
| 79 |
} |
| 80 |
|
| 81 |
if (missing(type)) { |
| 82 |
type <- switch(obj$se_type, CR0 = "CR0", CR2 = "CR2", stata = "CR1S", "No valid SE type") |
| 83 |
if (type == "No valid SE type") stop("You must specify a `type` of sandwich estimator to calculate or `obj` must include an `se_type` of 'CR0', 'CR2', or 'stata'.") |
| 84 |
} |
| 85 |
|
| 86 |
vcov_CR(obj, cluster = cluster, type = type, |
| 87 |
target = target, inverse_var = inverse_var, form = form) |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
#' Pulls the clustering variable from an iv_robust object, if it has one. |
| 92 |
#' |
| 93 |
#' @param obj an iv_robust object |
| 94 |
#' |
| 95 |
#' @return The data within the clustering variable |
| 96 |
#' @keywords internal |
| 97 |
#' @noRd |
| 98 |
|
| 99 |
findCluster.iv_robust <- function(obj) { |
| 100 |
|
| 101 |
if (!obj$clustered) return(NULL) |
| 102 |
|
| 103 |
model.frame(obj)[["(clusters)"]] |
| 104 |
} |
| 105 |
|
| 106 |
|
| 107 |
#---------------------------------------------- |
| 108 |
# model.frame |
| 109 |
#---------------------------------------------- |
| 110 |
|
| 111 |
#' @export |
| 112 |
|
| 113 |
model.frame.iv_robust <- function(formula, ...) { |
| 114 |
|
| 115 |
mf <- formula$model.frame |
| 116 |
if (!is.null(mf)) return(mf) |
| 117 |
|
| 118 |
fit_env <- environment(formula$terms) |
| 119 |
|
| 120 |
cl <- formula$call |
| 121 |
|
| 122 |
mf_args <- match(c("formula", "data", "weights", "subset", "clusters"), names(cl), 0L) |
| 123 |
|
| 124 |
mf_cl <- cl[c(1L, mf_args)] |
| 125 |
mf_cl$formula <- formula$terms |
| 126 |
mf_cl[[1L]] <- quote(stats::model.frame) |
| 127 |
mf <- eval(mf_cl, envir = fit_env) |
| 128 |
|
| 129 |
# If no fixed effects, we're done |
| 130 |
if (!isTRUE(formula$fes)) return(mf) |
| 131 |
|
| 132 |
# Build a second model.frame for the fixed-effects variables |
| 133 |
fe_args <- match(c("fixed_effects", "data", "subset"), names(cl), 0L) |
| 134 |
fe_cl <- cl[c(1L, fe_args)] |
| 135 |
names(fe_cl)[[2]] <- "formula" |
| 136 |
fe_cl[[2]] <- reformulate(all.vars(fe_cl[[2]])) |
| 137 |
fe_cl[[1L]] <- quote(stats::model.frame) |
| 138 |
mf_fe <- eval(fe_cl, envir = fit_env) |
| 139 |
|
| 140 |
# Reconcile any differences in omitted rows between the two model frames |
| 141 |
mf_omit <- na.action(mf) |
| 142 |
if (!is.null(names(mf_omit))) mf_omit <- names(mf_omit) |
| 143 |
fe_omit <- na.action(mf_fe) |
| 144 |
if (!is.null(names(fe_omit))) fe_omit <- names(fe_omit) |
| 145 |
|
| 146 |
if (identical(mf_omit, fe_omit)) { |
| 147 |
mf_combined <- cbind(mf, mf_fe) |
| 148 |
mf_combined_omit <- mf_omit |
| 149 |
} else { |
| 150 |
mf_combined <- cbind( |
| 151 |
mf[!(rownames(mf) %in% fe_omit), , drop = FALSE], |
| 152 |
mf_fe[!(rownames(mf_fe) %in% mf_omit), , drop = FALSE] |
| 153 |
) |
| 154 |
mf_combined_omit <- sort(c(mf_omit, fe_omit)) |
| 155 |
i_unique <- !duplicated(mf_combined_omit) |
| 156 |
mf_combined_omit <- mf_combined_omit[i_unique] |
| 157 |
class(mf_combined_omit) <- "omit" |
| 158 |
} |
| 159 |
|
| 160 |
attr(mf_combined, "terms") <- attr(mf, "terms") |
| 161 |
attr(mf_combined, "na.action") <- mf_combined_omit |
| 162 |
|
| 163 |
return(mf_combined) |
| 164 |
} |
| 165 |
|
| 166 |
|
| 167 |
#---------------------------------------------- |
| 168 |
# get X matrix (projected) |
| 169 |
#---------------------------------------------- |
| 170 |
|
| 171 |
#' @export |
| 172 |
|
| 173 |
model_matrix.iv_robust <- function(obj) { |
| 174 |
|
| 175 |
mf <- model.frame(obj) |
| 176 |
|
| 177 |
# Regressor matrix X |
| 178 |
X <- model.matrix(obj$terms_regressors, data = mf) |
| 179 |
|
| 180 |
# Instrument formula from the RHS of the | in the IV formula |
| 181 |
inst_formula <- as.formula(paste("~", deparse(obj$formula[[3]][[3]]))) |
| 182 |
Z <- model.matrix(inst_formula, data = mf) |
| 183 |
|
| 184 |
w <- weights(obj) |
| 185 |
|
| 186 |
# With fixed effects, residualize X and Z on the FE design matrix |
| 187 |
# (Frisch-Waugh-Lovell); the intercept is absorbed by the FEs. |
| 188 |
if (isTRUE(obj$fes)) { |
| 189 |
|
| 190 |
intercept_X <- colnames(X) == "(Intercept)" |
| 191 |
if (any(intercept_X)) X <- X[, !intercept_X, drop = FALSE] |
| 192 |
intercept_Z <- colnames(Z) == "(Intercept)" |
| 193 |
if (any(intercept_Z)) Z <- Z[, !intercept_Z, drop = FALSE] |
| 194 |
|
| 195 |
fe_formula <- as.formula(obj$call$fixed_effects) |
| 196 |
|
| 197 |
if (requireNamespace("fixest", quietly = TRUE)) { |
| 198 |
frame <- mf[attr(terms(fe_formula), "term.labels")] |
| 199 |
X <- fixest::demean(X = X, f = frame, weights = w) |
| 200 |
Z <- fixest::demean(X = Z, f = frame, weights = w) |
| 201 |
} else { |
| 202 |
fe_formula <- update(fe_formula, ~ . - 1) |
| 203 |
varnames <- all.vars(fe_formula) |
| 204 |
for (v in varnames) mf[[v]] <- as.factor(mf[[v]]) |
| 205 |
F_mat <- model.matrix(fe_formula, data = mf) |
| 206 |
if (is.null(w)) { |
| 207 |
X <- stats::lm.fit(F_mat, X)$residuals |
| 208 |
Z <- stats::lm.fit(F_mat, Z)$residuals |
| 209 |
} else { |
| 210 |
X <- stats::lm.wfit(F_mat, X, w)$residuals |
| 211 |
Z <- stats::lm.wfit(F_mat, Z, w)$residuals |
| 212 |
} |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
# Compute projected X: X_proj = Z (Z'WZ)^{-1} Z'W X |
| 217 |
if (is.null(w)) { |
| 218 |
X_proj <- Z %*% solve(crossprod(Z), crossprod(Z, X)) |
| 219 |
} else { |
| 220 |
wZ <- w * Z |
| 221 |
X_proj <- Z %*% solve(crossprod(wZ, Z), crossprod(wZ, X)) |
| 222 |
pos_wts <- w > 0 |
| 223 |
if (!all(pos_wts)) { |
| 224 |
X_proj <- X_proj[pos_wts, , drop = FALSE] |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
X_proj |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
#---------------------------------------------- |
| 233 |
# augmented model matrix (fixed effects) |
| 234 |
#---------------------------------------------- |
| 235 |
|
| 236 |
#' @export |
| 237 |
|
| 238 |
augmented_model_matrix.iv_robust <- function(obj, cluster, inverse_var, ignore_FE) { |
| 239 |
|
| 240 |
if (!isTRUE(obj$fes)) return(NULL) |
| 241 |
|
| 242 |
fe_formula <- as.formula(obj$call$fixed_effects) |
| 243 |
fe_formula <- update(fe_formula, ~ . + 0) |
| 244 |
|
| 245 |
mf <- model.frame(obj) |
| 246 |
|
| 247 |
varnames <- all.vars(fe_formula) |
| 248 |
for (v in varnames) mf[[v]] <- as.factor(mf[[v]]) |
| 249 |
|
| 250 |
model.matrix(fe_formula, data = mf) |
| 251 |
} |
| 252 |
|
| 253 |
|
| 254 |
#--------------------------------------- |
| 255 |
# Get bread matrix and scaling constant |
| 256 |
#--------------------------------------- |
| 257 |
|
| 258 |
#' @export |
| 259 |
|
| 260 |
bread.iv_robust <- function(x, ...) { |
| 261 |
|
| 262 |
N <- nobs(x) |
| 263 |
|
| 264 |
XZ <- model_matrix(x) |
| 265 |
|
| 266 |
if (x$weighted) { |
| 267 |
w <- weights(x) |
| 268 |
if (!is.null(w)) { |
| 269 |
pos_wts <- w > 0 |
| 270 |
if (!all(pos_wts)) w <- w[pos_wts] |
| 271 |
} |
| 272 |
XtWX <- crossprod(XZ, w * XZ) |
| 273 |
} else { |
| 274 |
XtWX <- crossprod(XZ) |
| 275 |
} |
| 276 |
|
| 277 |
N * solve(XtWX) |
| 278 |
} |
| 279 |
|
| 280 |
#---------------------------------------------- |
| 281 |
# get residuals |
| 282 |
#---------------------------------------------- |
| 283 |
|
| 284 |
#' @export |
| 285 |
|
| 286 |
residuals_CS.iv_robust <- function(obj) { |
| 287 |
|
| 288 |
mf <- model.frame(obj) |
| 289 |
r <- mf[[obj$outcome]] - obj$fitted.values |
| 290 |
|
| 291 |
w <- weights(obj) |
| 292 |
if (!is.null(w)) { |
| 293 |
pos_wts <- w > 0 |
| 294 |
if (!all(pos_wts)) r <- r[pos_wts] |
| 295 |
} |
| 296 |
|
| 297 |
r |
| 298 |
} |
| 299 |
|
| 300 |
#---------------------------------------------- |
| 301 |
# na.action |
| 302 |
#---------------------------------------------- |
| 303 |
|
| 304 |
#' @export |
| 305 |
|
| 306 |
na.action.iv_robust <- function(object, ...) { |
| 307 |
na.action(model.frame(object)) |
| 308 |
} |
| 309 |
|
| 310 |
# coef_CS() - use default |
| 311 |
# targetVariance() - use default |
| 312 |
# weightMatrix() - use default |
| 313 |
# v_scale() - use default |