如何在R中提取线性模型的残差和预测值?
残差是实际值与预测值之间的差值,而预测值是线性模型对实际值的预测值。要从线性模型中提取残差和预测值,我们需要使用resid和predict函数以及模型对象。
请考虑以下数据框:
示例
x1<-rnorm(20,14,3.25) y1<-rnorm(20,6,0.35) df1<-data.frame(x1,y1) df1
输出
x1 y1 1 14.565652 6.506233 2 13.350634 6.481486 3 8.636661 5.806754 4 11.495087 6.164963 5 12.159347 6.749101 6 16.642371 6.061237 7 9.137345 6.121711 8 12.616223 5.911341 9 10.109950 5.819494 10 15.953629 6.067601 11 13.579602 6.438686 12 14.708544 5.175576 13 19.234206 6.926994 14 13.539790 5.669169 15 15.101462 6.253202 16 13.812982 6.042699 17 12.680245 6.019822 18 15.292250 6.174533 19 12.759720 5.648624 20 11.371360 5.879896
创建x1和y1之间的线性模型:
Model1<-lm(y1~x1,data=df1)
从Model1中查找残差和预测值:
resid(Model1)
1 2 3 4 5 6 0.34576809 0.38483276 -0.04232628 0.16576122 0.71501218 -0.20829562 7 8 9 10 11 12 0.24633525 -0.14674241 -0.10696233 -0.16575896 0.33000726 -0.99239332 13 14 15 16 17 18 0.52134132 -0.43741908 0.06459654 -0.07823690 -0.04162379 -0.02409178 19 20 -0.41699579 -0.11280836 > predict(Model1) 1 2 3 4 5 6 7 8 6.160465 6.096654 5.849080 5.999202 6.034088 6.269532 5.875376 6.058083 9 10 11 12 13 14 15 16 5.926456 6.233360 6.108679 6.167970 6.405653 6.106588 6.188605 6.120936 17 18 19 20 6.061445 6.198625 6.065619 5.992704
示例
x2<-rpois(20,5) y2<-rpois(20,2) df2<-data.frame(x2,y2) df2
输出
x2 y2 1 7 0 2 5 1 3 3 1 4 3 2 5 6 3 6 2 8 7 4 2 8 6 0 9 9 1 10 3 0 11 4 3 12 7 1 13 6 2 14 6 0 15 5 2 16 9 1 17 5 3 18 5 2 19 6 5 20 7 0
创建x2和y2之间的线性模型:
Model2<-lm(y2~x2,data=df2)
从Model2中查找残差和预测值:
resid(Model2)
1 2 3 4 5 6 -1.15697674 -1.02325581 -1.88953488 -0.88953488 1.40988372 4.67732558 7 8 9 10 11 12 -0.45639535 -1.59011628 0.70930233 -2.88953488 0.54360465 -0.15697674 13 14 15 16 17 18 0.40988372 -1.59011628 -0.02325581 0.70930233 0.97674419 -0.02325581 19 20 3.40988372 -1.15697674
predict(Model2)
1 2 3 4 5 6 7 8 1.1569767 2.0232558 2.8895349 2.8895349 1.5901163 3.3226744 2.4563953 1.5901163 9 10 11 12 13 14 15 16 0.2906977 2.8895349 2.4563953 1.1569767 1.5901163 1.5901163 2.0232558 0.2906977 17 18 19 20 2.0232558 2.0232558 1.5901163 1.1569767
广告