简体   繁体   中英

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

I have the following code, which works fine, but I am wondering if the last 4 lines could be run using a for loop? I was not sure how to code this, given the number-letter combinations.

 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")

You can create a vector of column names that you want to plot for and then use 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))

Also with a for loop :

list_plots <- vector('list', length(cols))

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

list_plots would have list of plots where each individual plot can be accessed like list_plots[[1]] , list_plots[[2]] and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM