计算二元线性回归系数

时间:2017-10-04 23:40:02

标签: r matrix regression multiplication

Question to be answered

有谁知道如何在两行代码中解决附加问题?我相信as.matrix可以创建矩阵X,然后使用X %*% Xt(X)solve(X)来获得答案。但是,它似乎没有起作用。任何答案都会有所帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

我建议使用read.csv代替read.table

在这个帖子中查看两个函数的区别对你有用:read.csv vs. read.table

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 

答案 1 :(得分:0)

根据@kon_u的答案,这是一个用手做的例子:

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
相关问题