假设我有以下数据帧:
library(tidyverse)
fit <- lm(speed ~ dist, data = cars)
select(broom::augment(fit), .fitted:.std.resid) -> dt
names(dt) <- substring(names(dt), 2)
Run Code Online (Sandbox Code Playgroud)
我想创建一个残差图的网格使用purrr.例如,到目前为止,我有2个诊断图的公式:
residual <- function(model) {ggplot(model, aes(fitted, resid)) +
geom_point() +
geom_hline(yintercept = 0) +
geom_smooth(se = FALSE)}
stdResidual <- function(model) {ggplot(model, aes(fitted, std.resid)) +
geom_point() +
geom_hline(yintercept = 0) +
geom_smooth(se = FALSE)}
Run Code Online (Sandbox Code Playgroud)
我将公式存储在我计划针对强化数据集运行的列表中dt.
formulas <- tibble(charts = list(residual, stdResidual))
# A tibble: 2 x 1
charts
<list>
1 <fun>
2 <fun>
Run Code Online (Sandbox Code Playgroud)
现在我需要传递dt给列chart中的每个元素formulas.我实际上也试图将两者结合使用gridExtra,但是现在如果我至少可以渲染它们,我会感到满意.我想我应该运行类似的东西
pwalk(list(dt, formulas), ???)
Run Code Online (Sandbox Code Playgroud)
但是我不知道我应该使用什么函数???来渲染图.
设置函数来绘制每个函数,就像你上面所做的那样:
diagplot_resid <- function(df) {
ggplot(df, aes(.fitted, .resid)) +
geom_hline(yintercept = 0) +
geom_point() +
geom_smooth(se = F) +
labs(x = "Fitted", y = "Residuals")
}
diagplot_stdres <- function(df) {
ggplot(df, aes(.fitted, sqrt(.std.resid))) +
geom_hline(yintercept = 0) +
geom_point() +
geom_smooth(se = F) +
labs(x = "Fitted", y = expression(sqrt("Standardized residuals")))
}
diagplot_qq <- function(df) {
ggplot(df, aes(sample = .std.resid)) +
geom_abline(slope = 1, intercept = 0, color = "black") +
stat_qq() +
labs(x = "Theoretical quantiles", y = "Standardized residuals")
}
Run Code Online (Sandbox Code Playgroud)
然后在列表中调用每个,将数据帧作为第二个参数.这里是invoke一个函数列表,并将它们并行应用于函数参数列表.由于第二个列表中只有一个元素,因此invoke_map循环遍历它们.
fit <- lm(mpg~wt, mtcars)
df_aug <- augment(fit)
purrr::invoke_map(.f = list(diagplot_resid, diagplot_stdres, diagplot_qq),
.x = list(list(df_aug))) %>%
gridExtra::grid.arrange(grobs = ., ncol = 2,
top = paste("Diagnostic plots for",
as.expression(fit$call)))
Run Code Online (Sandbox Code Playgroud)