2017-10-04 77 views
-3

Question to be answered计算系数

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

+1

请告诉我们你到目前为止试过的东西。这将有助于您生成[可重现的示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) –

回答

1

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

这将是有益的,你走过去的两个功能在这个线程的区别:基于@kon_u的答案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 
0

,这里是一个用手做的例子:

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 
+0

请注意,此公式允许您也计算多元线性回归的系数。 – ANG