这里我有两个名为 model1
的数据框和model2
:
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 具有相同斜率和截距的两个模型的图表:
我的目的是计算模型 2 中的残差,但正如您所见,斜率和截距来自模型 1。
希望清楚,欢迎任何帮助!
最佳答案
只需使用 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
关于r - 计算残差,但根据 R 中的其他斜率和截距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226659/