variance-covariance matrix in R

馋奶兔 提交于 2021-02-11 11:51:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!