R 二元线性回归系数的计算

R 二元线性回归系数的计算,r,matrix,regression,multiplication,R,Matrix,Regression,Multiplication,有人知道如何用两行代码解决附带的问题吗?我相信as.matrix可以创建一个矩阵X,然后使用X%*%X、tX和solveX得到答案。然而,它似乎不起作用。任何答案都会有帮助,谢谢 我建议使用read.csv而不是read.table 您可以在此线程中查看两个函数的差异: 根据@kon_的答案,这里有一个手工操作的示例: df <- read.csv("http://pengstats.macssa.com/download/rcc/lmdata.csv") model1 <- lm(

有人知道如何用两行代码解决附带的问题吗?我相信as.matrix可以创建一个矩阵X,然后使用X%*%X、tX和solveX得到答案。然而,它似乎不起作用。任何答案都会有帮助,谢谢

我建议使用read.csv而不是read.table

您可以在此线程中查看两个函数的差异:


根据@kon_的答案,这里有一个手工操作的示例:

df <- read.csv("http://pengstats.macssa.com/download/rcc/lmdata.csv")
model1 <- lm(y ~ x1 + x2, data = df)
coefficients(model1) # get the coefficients of your regression model1
summary(model1) # get the summary of model1 

### Based on the formula
X <- cbind(1, df$x1, df$x2) # the column of 1 is to consider the intercept
Y <- df$y
bhat <- solve(t(X) %*% X) %*% t(X) %*% Y # coefficients 
bhat # Note that we got the same coefficients with the lm function

请告诉我们你到目前为止都做了些什么。请注意,这个公式也允许您计算多元线性回归的系数。
df <- read.csv("http://pengstats.macssa.com/download/rcc/lmdata.csv")
model1 <- lm(y ~ x1 + x2, data = df)
coefficients(model1) # get the coefficients of your regression model1
summary(model1) # get the summary of model1 

### Based on the formula
X <- cbind(1, df$x1, df$x2) # the column of 1 is to consider the intercept
Y <- df$y
bhat <- solve(t(X) %*% X) %*% t(X) %*% Y # coefficients 
bhat # Note that we got the same coefficients with the lm function