首页 > 解决方案 > R:遍历 ggplot 的回归模型列表

问题描述

我有六个回归模型存储在不同的变量中。我尝试使用以下方法将它们放入列表中:

modellist <- c(model1, model2....)

我想使用以下循环:

for (x in 1:6) {

  p1 <- ggplot(modellist[[x]], aes(.fitted, .resid))+geom_point()

  p1 <- p1+stat_smooth(method="loess")+
        geom_hline(yintercept=0, col="red", linetype="dashed")

  plotlist <- c(plotlist, p1)
}

...创建一个我可以显示的图列表marrangeGrob

ggplot不接受modellist[[x]]作为输入,而是给出错误:

Error: ggplot2 doesn't know how to deal with data of class numeric 

如何存储模型以迭代它们?

标签: rlistggplot2regression

解决方案


扩展我的评论,一个lapply例子:

library(mtcars)
library(ggplot2)
model1 <- lm(mpg ~ cyl, data=mtcars)
model2 <- lm(mpg ~ disp, data=mtcars)
modellist <- list(model1, model2)

ggplot_linear_model <- function(lm.input) {
  x <- ggplot(lm.input, aes(.fitted, .resid))+
       geom_point()+
       stat_smooth(method="loess")+
       geom_hline(yintercept=0, col="red", linetype="dashed")
  return(x)
}

lapply(modellist, ggplot_linear_model)

推荐阅读