问题
I have the data frame below and from there I've calculated the matrix b from the betas of coefficients of my linear regression model. How do I create the variance-covariance matrix in R, or s^2_b?
y <- c(42, 33, 75, 28, 91, 55)
int <- c(1, 1, 1, 1, 1, 1)
x1 <- c(7, 4, 16, 3, 21, 8)
x2 <- c(33, 41, 7, 49, 5, 31)
df <- data.frame(y, x1, x2)
mod1 <- lm(y ~ x1 + x2, data = df)
# b
iint <- summary(mod1)$coefficients[[1]]
xx1 <- summary(mod1)$coefficients[[2]]
xx2 <- summary(mod1)$coefficients[[3]]
b <- matrix(c(iint, xx1, xx2), nrow=3)
# matrices of x and y
Y <- matrix(df$y)
X <- matrix(c(1, 1, 1, 1, 1, 1, 7, 4, 16, 3, 21, 8, 33, 41, 7, 49, 5, 31), nrow=6)
回答1:
We can use vcov to get the variance-covariance matrix
vcov(mod1)
It can be manually calculated as well
all.equal(vcov(mod1),
solve(t(X) %*% X) * sum(mod1$residuals^2)/(nrow(df) - ncol(df) + 1 -1),
check.attributes = FALSE)
# [1] TRUE
来源:https://stackoverflow.com/questions/59277529/variance-covariance-matrix-in-r