【发布时间】:2017-03-17 17:54:38
【问题描述】:
我的目标是在去除异常值后获得数据集及其相关残差的线性回归模型。
用'iris'数据集来说明:
这个原始模型没有删除任何观察结果
(模型1)
library(dplyr)
library(magrittr)
library(broom)
iris %>%
+ do(tidy(lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .)))
term estimate std.error statistic p.value
1 (Intercept) 2.3903891 0.26226815 9.114294 5.942826e-16
2 Sepal.Width 0.4322172 0.08138982 5.310458 4.025982e-07
3 Petal.Length 0.7756295 0.06424566 12.072869 1.151112e-23
4 Speciesversicolor -0.9558123 0.21519853 -4.441537 1.759999e-05
5 Speciesvirginica -1.3940979 0.28566053 -4.880261 2.759618e-06
但我想移除一些异常值(基于 .cooksd)进行改造。即:
(模型2)
iris %>%
+ do(augment(lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .))) %>%
+ filter(.cooksd < 0.03) %>%
+ do(tidy(lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .)))
term estimate std.error statistic p.value
1 (Intercept) 2.3927287 0.23718040 10.088223 2.875549e-18
2 Sepal.Width 0.4150542 0.07374143 5.628508 9.775805e-08
3 Petal.Length 0.8035635 0.05975821 13.446914 7.229176e-27
4 Speciesversicolor -0.9858935 0.19651867 -5.016793 1.589618e-06
5 Speciesvirginica -1.4841365 0.26399083 -5.621924 1.008374e-07
保存这些模型:
lm_model2 <- iris %>%
do(augment(lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .))) %>%
filter(.cooksd < 0.03) %>%
lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .)
lm_model1 <- iris %>%
lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species, .)
做到了,是否可以根据第二个模型得到数据集的回归残差。
我能想到的唯一解决方案是使用模型 2 的系数来间接计算这些,即:
Residual = 2.3927287 + 0.4150542 * Sepal.Width + 0.8035635 * Petal.Length + [-0.9858935 * Speciesversicolor] or + [-1.4841365 * Speciesvirginica] - Sepal.Length
有没有更好的方法?类似于:
residuals <- obtain_residuals(iris, lm_model2)
非常感谢。
【问题讨论】:
-
您是否保存了您的
lm模型对象? -
为什么不Sepal.Length - 预测(模型)???
-
我想我的问题暗示了这一点。
-
添加了保存对象的代码
-
残差针对数据集的每个观察(行)而不是模型变量(列)运行。
lm_model1和lm_model2是作为数据框的模型摘要,未与原始数据集对齐 (N=150)。
标签: r linear-regression