r - 计算残差,但根据 R 中的其他斜率和截距

标签 r

这里我有两个名为 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 具有相同斜率和截距的两个模型的图表:

enter image description here

我的目的是计算模型 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/

相关文章:

r - 使用百分比创建马赛克图

mysql - 如何在MySql或R中获取天数桶的计数

R:如何在 XGBoost 中使用多个 GPU?

r - 为什么 R 在我的(较强的)台式机上比在我的(较弱的)笔记本电脑上慢?

减少使用 kable(, format = 'markdown' ) 创建的表中列之间的间距

r - 为什么 `print.function` 不同意用 `substitute()` 创建的函数体?

r - 如何在ggplot2中为相同的美学设置多个图例?

r - 如何为R中的列中的元素分配顺序?

r - 如何将数据框 1 的每一行与数据框 2 的每一行进行比较?

r - R中的非线性逻辑回归包