【问题标题】:How to use a for loop in R to create multiple plots如何在 R 中使用 for 循环创建多个绘图
【发布时间】:2021-01-10 08:29:17
【问题描述】:

我有以下代码,它工作正常,但我想知道最后 4 行是否可以使用 for 循环运行?鉴于数字-字母组合,我不确定如何编码。

 library(ggpubr)
 set.seed(12345)
 df1 = data.frame(a=c(rep("a",8), rep("b",5), rep("c",7), rep("d",10)), 
      b=rnorm(30, 6, 2), 
      c=rnorm(30, 12, 3.5), 
      d=rnorm(30, 8, 3),
      e=rnorm(30, 4, 1),
      f=rnorm(30, 16, 6)
      )
 plot1 <- ggscatter (df1, x="b", y="c")
 plot2 <- ggscatter (df1, x="b", y="d")
 plot3 <- ggscatter (df1, x="b", y="e")
 plot4 <- ggscatter (df1, x="b", y="f")

【问题讨论】:

    标签: r for-loop ggpubr


    【解决方案1】:

    您可以创建要为其绘制的列名向量,然后使用lapply

    library(ggpubr)
    cols <- c('c', 'd', 'e', 'f')
    #Or use
    cols <- names(df1)[-c(1:2)]
    
    list_plots <- lapply(cols, function(x) ggscatter(df1, 'b', x))
    

    还有for 循环:

    list_plots <- vector('list', length(cols))
    
    for(i in seq_along(cols)) {
      list_plots[[i]] <- ggscatter(df1, 'b', cols[i])
    }
    

    list_plots 将有一个地块列表,其中每个单独的地块都可以访问,例如list_plots[[1]]list_plots[[2]] 等等。

    【讨论】:

    • 太棒了!非常感谢这两个选项,Ronak。
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 2021-05-25
    • 2019-12-09
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多