Debian Codegraph @

R/lm.R

raw
1 #-------------------------------------
2 # vcovCR with defaults
3 #-------------------------------------
4
5 #' Cluster-robust variance-covariance matrix for an lm 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{lm}} object.
9 #'
10 #' @param cluster Expression or vector indicating which observations belong to
11 #' the same cluster. Required for \code{lm} 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 an identity matrix.
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 #' data("ChickWeight", package = "datasets")
27 #' lm_fit <- lm(weight ~ Time + Diet:Time, data = ChickWeight)
28 #' vcovCR(lm_fit, cluster = ChickWeight$Chick, type = "CR2")
29 #'
30 #' if (requireNamespace("plm", quietly = TRUE)) withAutoprint({
31 #'
32 #' data("Produc", package = "plm")
33 #' lm_individual <- lm(log(gsp) ~ 0 + state + log(pcap) + log(pc) + log(emp) + unemp, data = Produc)
34 #' individual_index <- !grepl("state", names(coef(lm_individual)))
35 #' vcovCR(lm_individual, cluster = Produc$state, type = "CR2")[individual_index,individual_index]
36 #'
37 #' # compare to plm()
38 #' plm_FE <- plm::plm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp,
39 #' data = Produc, index = c("state","year"),
40 #' effect = "individual", model = "within")
41 #' vcovCR(plm_FE, type="CR2")
42 #'
43 #' })
44 #'
45 #' @export
46
47 vcovCR.lm <- function(obj, cluster, type, target = NULL, inverse_var = NULL, form = "sandwich", ...) {
48 if (missing(cluster)) stop("You must specify a clustering variable.")
49 if (is.null(inverse_var)) inverse_var <- is.null(weights(obj)) & is.null(target)
50 vcov_CR(obj, cluster = cluster, type = type,
51 target = target, inverse_var = inverse_var, form = form)
52 }
53
54 # model_matrix()
55 # residuals_CS()
56 # coef()
57 # nobs()
58 # targetVariance()
59 # weightMatrix()
60
61
62 #---------------------------------------
63 # Get bread matrix and scaling constant
64 #---------------------------------------
65
66 # bread.lm() is in sandwich package
67
68 #' @export
69
70 v_scale.lm <- function(obj) {
71 as.vector(sum(summary(obj)$df[1:2]))
72 }