如何从lm()返回预测值,残差和R方? [英] How to return predicted values, residuals, R square from lm()?
问题描述
这段代码将返回系数:intercept,slop1,slop2
this piece of code will return coefficients :intercept , slop1 , slop2
set.seed(1)
n=10
y=rnorm(n)
x1=rnorm(n)
x2=rnorm(n)
lm.ft=function(y,x1,x2)
return(lm(y~x1+x2)$coef)
res=list();
for(i in 1:n){
x1.bar=x1-x1[i]
x2.bar=x2-x2[i]
res[[i]]=lm.ft(y,x1.bar,x2.bar)
}
如果我输入:
> res[[1]]
我得到:
(Intercept) x1 x2
-0.44803887 0.06398476 -0.62798646
我们如何返回预测值,残差,R方,.. etc等?
How can we return predicted values,residuals,R square, ..etc?
我需要一些常规信息以从摘要中提取所需的内容吗?
I need something general to extract whatever I need from the summary?
推荐答案
这里发生了几件事.
首先,最好将变量组合到data.frame中:
First, you are better off combining your variables into a data.frame:
df <- data.frame(y=rnorm(10), x1=rnorm(10), x2 = rnorm(10))
fit <- lm(y~x1+x2, data=df)
如果这样做,那么使用模型对新数据集进行预测要容易得多.
If you do this, then using you model for prediction with a new dataset is is much easier.
第二,可以从模型本身访问一些拟合统计信息,而某些可以从summary(fit)
访问.
Second, some of the statistics of the fit are accessible from the model itself, and some are accessible from summary(fit)
.
coef <- coefficients(fit) # coefficients
resid <- residuals(fit) # residuals
pred <- predict(fit) # fitted values
rsq <- summary(fit)$r.squared # R-sq for the fit
se <- summary(fit)$sigma # se of the fit
要获取系数的统计信息,您需要使用摘要:
To get the statistics of the coefficients, you need to use summary:
stat.coef <- summary(fit)$coefficients
coef <- stat.coef[,1] # 1st column: coefficients (same as above)
se.coef <- stat.coef[,2] # 2nd column: se for each coef
t.coef <- stat.coef[,3] # 3rd column: t-value for each coef
p.coef <- stat.coef[,4] # 4th column: p-value for each coefficient
这篇关于如何从lm()返回预测值,残差和R方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!