计算残差,但从R中的其他斜率和截距计算

时间:2015-07-05 02:21:25

标签: r

我在这里有两个名为model1model2的数据框:

class1<-c(1,2,3,4,5,6,7)
abund1<-c(10.4,8.9,9.1,7.5,7.1,5.1,3.2)
model1<-data.frame(class1,abund1)
class2<-c(1,2,3,4,5,6,7)
abund2<-c(9.5,8.4,8,6.3,6,2.4,1.2)
model2<-data.frame(class2,abund2)

首先,我使用lm提取model1的斜率和截距:

model1_lm<-lm(abund1~class1, data=model1)
model1_lm$coefficients[1]
11.7857                    #intercept from the model1
model1_lm$coefficients[2]
-1.1143                    #slope from the model1

我想知道是否可以从class2-abund2计算地块model2的残差(即保留值 - 预测值),但使用model1的斜率和截距}。

在这里,我向您展示了两个模型的图形,它们具有相同的斜率和模型1的截距:

enter image description here

我的目的是计算模型2中的残差,但正如您所看到的,斜率和截距来自模型1

希望明确,欢迎任何帮助!

1 个答案:

答案 0 :(得分:2)

只需将predict与拟合的模型一起使用,model2作为新数据:

# predict will look for a column called "class1" in the newdata argument, so we need to provide it.
# observed - predicted
model2$abund2 - predict(model1_lm, data.frame(class1 = model2$class2))
#         1          2          3          4          5          6          7 
#-1.1714286 -1.1571429 -0.4428571 -1.0285714 -0.2142857 -2.7000000 -2.7857143
相关问题