如何在 R 中使用 for 循环创建多个图

How to use a for loop in R to create multiple plots

我有以下代码,工作正常,但我想知道最后 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")

您可以创建一个包含要绘制的列名称的向量,然后使用 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]] 等等。