【发布时间】:2017-07-21 20:43:00
【问题描述】:
我想将 3 个线性模型应用于我的数据,并为每个模型提取残差。我想知道是否有一种方法可以结合使用 dplyr 和 purrr 对每个模型应用相同的步骤:
我想保留:
- 每个模型的
lm对象 - 每个模型的
augment输出 - 每个模型的残差
这是一个分析mpg 数据集的工作示例:
library(dplyr)
library(tidyr)
library(purrr)
library(broom)
library(ggplot2)
这是我想为我的 lm 使用的三个不同的公式
f1 = hwy ~ cyl
f2 = hwy ~ displ
f3 = hwy ~ cyl + displ
lin_mod = function(formula) {
function(data) {
lm(formula, data = data)
}
}
这是我为单个公式提取残差的方法:
mpg %>%
group_by(manufacturer) %>%
nest() %>%
mutate(model = map(data, lin_mod(f1)),
aug = map(model, augment),
res = map(aug, ".resid"))
但是,这种技术对于所有公式来说似乎都是一种糟糕的方法,因为我重写了很多代码:
mpg %>%
group_by(manufacturer) %>%
nest() %>%
mutate(model1 = map(data, lin_mod(f1)),
aug1 = map(model1, augment),
res1 = map(aug1, ".resid"),
model2 = map(data, lin_mod(f2)),
aug2 = map(model2, augment),
res2 = map(aug2, ".resid"),
model3 = map(data, lin_mod(f3)),
aug3 = map(model3, augment),
res3 = map(aug3, ".resid"))
如何以优雅的方式将此函数应用于每个公式?我在想 mutate_all,或将公式放入列表中可能会有所帮助,但可惜我被卡住了。
【问题讨论】: