【问题标题】:R: iterate through list of regression models for ggplot [closed]R:遍历ggplot的回归模型列表[关闭]
【发布时间】:2018-12-01 01:50:33
【问题描述】:

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

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 

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

【问题讨论】:

  • 看起来你用c() 将它们连接成一个向量,而不是把它们放在一个列表中。尝试使用list()
  • 哇,就是这样。谢谢!
  • 鉴于循环在 R 世界中经常不受欢迎,另一种方法是定义要应用于每个列表项的函数,然后使用类似 lapply(modellist, the_function_you_defined) 的函数。
  • 如果您坚持使用for 循环,您可能需要将其更改为for (x in 1:length(modellist)),以防您的模型数量发生变化。
  • @AdamSmith 通常我会reject and edit any suggested edit 留下或改进“谢谢”行,但看到您在编辑上付出的努力比标准作者更多,我已经批准了。请,请,尽可能删除这些类型的线条。见meta

标签: r list ggplot2 regression


【解决方案1】:

扩展我的评论,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)

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2019-04-03
    • 1970-01-01
    • 2019-12-30
    • 2019-08-03
    • 1970-01-01
    • 2016-09-19
    • 2014-09-26
    • 2013-07-13
    相关资源
    最近更新 更多