Reputation: 1353
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")
Upvotes: 0
Views: 1236
Reputation: 389135
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.
Upvotes: 1