Last active
November 8, 2021 15:26
-
-
Save donaldRwilliams/abb377460603e02ce335e318d26ad6f9 to your computer and use it in GitHub Desktop.
estimate covariance matrix with regression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# estimate covariance matrix with regression | |
library(GGMnonreg) | |
p = 20 | |
pcors = GGMnonreg::gen_net(p = p) | |
y = MASS::mvrnorm(n = 500, | |
mu = rep(0, p), | |
Sigma = pcors$cors) | |
y = scale(y, scale = F) | |
precision_reg = matrix(0, p, p) | |
precision = solve(cov(y)) | |
for(i in 1:p){ | |
fit_i <- lm(y[,i] ~ 0 + y[,-i]) | |
res_var <- var(residuals(fit_i)) | |
precision_reg[i,-i] <- (-coef(fit_i)) / res_var | |
precision_reg[i,i] <- 1/res_var | |
} | |
all.equal(round(precision_reg, 5), round(precision, 5)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment