R中的方差-协方差矩阵

car*_*lie 1 r

我有下面的数据框,从那里我根据线性回归模型的系数贝塔计算了矩阵 b 。如何在 R 或 中创建方差-协方差矩阵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)
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们可以用它vcov来得到方差-协方差矩阵

vcov(mod1)
Run Code Online (Sandbox Code Playgroud)

也可以手动计算

all.equal(vcov(mod1), 
   solve(t(X) %*% X) * sum(mod1$residuals^2)/(nrow(df) - ncol(df) + 1 -1),
       check.attributes = FALSE)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)