如何从R中的方差-协方差矩阵中获得回归系数?

如何从R中的方差-协方差矩阵中获得回归系数?,r,matrix,regression,linear-regression,covariance,R,Matrix,Regression,Linear Regression,Covariance,我想通过使用矩阵代数来计算回归系数,一直计算出一个多元回归的例子 #create vectors -- these will be our columns y <- c(3,3,2,4,4,5,2,3,5,3) x1 <- c(2,2,4,3,4,4,5,3,3,5) x2 <- c(3,3,4,4,3,3,4,2,4,4) #create matrix from vectors M <- cbind(y,x1,x2) k <- ncol(M) #number o

我想通过使用矩阵代数来计算回归系数,一直计算出一个多元回归的例子

#create vectors -- these will be our columns
y <- c(3,3,2,4,4,5,2,3,5,3)
x1 <- c(2,2,4,3,4,4,5,3,3,5)
x2 <- c(3,3,4,4,3,3,4,2,4,4)

#create matrix from vectors
M <- cbind(y,x1,x2)
k <- ncol(M) #number of variables
n <- nrow(M) #number of subjects

#create means for each column
M_mean <- matrix(data=1, nrow=n) %*% cbind(mean(y),mean(x1),mean(x2)); M_mean

#creates a difference matrix which gives deviation scores
D <- M - M_mean; D

#creates the covariance matrix, the sum of squares are in the diagonal and the sum of cross products are in the off diagonals.  
C <-  t(D) %*% D; C 
我可以看到最终的值应该是-.19,-.01,以及这个计算之前的矩阵是什么样子

E<-matrix(c(10.5,3,3,4.4),nrow=2,ncol=2)
F<-matrix(c(-2,-.6),nrow=2,ncol=1)
但我不知道如何从方差-协方差矩阵中创建这些,从而使用矩阵代数得到系数


希望你能帮忙

您可能想要这样的东西:

X <- cbind(1, x1, x2)
C <- t(X) %*% X # No need of centering the columns with means
D <- t(X) %*% y

coef <- t(solve(C) %*% D)
coef
#                      x1           x2
# [1,] 4.086022 -0.188172 -0.008064516

lm(y~x1+x2)$coef # coefficients with R lm()
# (Intercept)           x1           x2 
# 4.086021505 -0.188172043 -0.008064516 

我可以看出你在做:

答案不完全是你想要的,因为它通过通常的正常方程来估计:

关于后者已经有了一条线索:这里我重点关注前者

其实你已经很接近了。您已获得混合协方差C:

从你对E和F的定义,你知道你需要子矩阵来继续。事实上,您可以进行矩阵子集设定,而不是手动插补:

E <- C[2:3, 2:3]

#     x1  x2
#x1 10.5 3.0
#x2  3.0 4.4

F <- C[2:3, 1, drop = FALSE]  ## note the `drop = FALSE`

#      y
#x1 -2.0
#x2 -0.6
其他建议

您可以通过colMeans查找列平均值,而不是矩阵乘法读取?colMeans; 您可以使用扫描读取?扫描来执行定心; 使用crossprod而不是tD%*%D读取?crossprod。 下面是我要做的一个环节:

y <- c(3,3,2,4,4,5,2,3,5,3)
x1 <- c(2,2,4,3,4,4,5,3,3,5)
x2 <- c(3,3,4,4,3,3,4,2,4,4)

M <- cbind(y,x1,x2)
M_mean <- colMeans(M)
D <- sweep(M, 2, M_mean)
C <- crossprod(D)

E <- C[2:3, 2:3]
F <- C[2:3, 1, drop = FALSE]
c(solve(E, F))
# [1] -0.188172043 -0.008064516

我不确定你在那里做什么,但这不是OLS回归:矩阵平方和的倒数.xx乘以矩阵平方和.xy应该给我回归系数。我应该在有时间的时候修改这个答案。目前它的结构还不完善。简单地说,如果我们有一个响应向量y和一个不包括截距的自变量矩阵X,这些变量的斜率是b
c(solve(E, F))  ## use `c` to collapse matrix into a vector
# [1] -0.188172043 -0.008064516
y <- c(3,3,2,4,4,5,2,3,5,3)
x1 <- c(2,2,4,3,4,4,5,3,3,5)
x2 <- c(3,3,4,4,3,3,4,2,4,4)

M <- cbind(y,x1,x2)
M_mean <- colMeans(M)
D <- sweep(M, 2, M_mean)
C <- crossprod(D)

E <- C[2:3, 2:3]
F <- C[2:3, 1, drop = FALSE]
c(solve(E, F))
# [1] -0.188172043 -0.008064516