This could be achieved like so:
When using loops I prefer to put the plotting code in a separate function. Makes it easier to check, to debug and results (in my opinion) in cleaner and clearer code. Therefore I put the plotting code in a function make_plot
.
I did the same for your inner loop. I created a function
inner_loop <- function(x) {
# Create list
List <- lapply(seq_along(cylinder), make_plot)
# Wrap plots
wrap_plots(List, nrow = 1)
}
which loops over the cylinder
s, makes a plot for each value and glues the plots together.
- After these inital steps we can easily loop over
repeats
, call function inner_loop
and finally glue the resulting list of pages together:
repeats <- c(1,2,3) # for the outer loop.
pages <- lapply(repeats, inner_loop)
wrap_plots(pages, ncol = 1)
Full reproducible code:
library(dplyr)
library(ggplot2)
library(patchwork)
cylinder <- unique(mtcars$cyl)
make_plot <- function(value) {
m <- mtcars %>%
filter(cyl == cylinder[value]) %>%
group_by(gear) %>%
summarise(number = n(), average = mean(mpg), se = sd(mpg))
#print(m) # reporting the numbers
m %>%
mutate(gear = factor(gear, levels = unique(gear))) %>%
ggplot() +
geom_bar(aes(x = gear, y = average), stat = "identity", fill = "red") +
geom_errorbar(aes(x = gear, ymin = average - se, ymax = average + se), width = 0.2, colour = "black", alpha = 1, size = 1) +
xlab("gears") +
ylab("average mpg") +
ggtitle(paste("cylinder:", value)) +
theme(axis.ticks.x = element_blank())
}
inner_loop <- function(x) {
# Create list
List <- lapply(seq_along(cylinder), make_plot)
# Wrap plots
wrap_plots(List, nrow = 1)
}
# Outer loop
repeats <- c(1,2,3) # for the outer loop.
pages <- lapply(repeats, inner_loop)
wrap_plots(pages, ncol = 1)
EDIT I adapted the example and the code a bit. Now the outer loop loops over the gear
s. The value of gear
is passed as an parameter to the inner loop and to the plot function, where it can be used to filter the dataset accordingly. As a result you nine different plots. One row per gear and the columns for the cylinders.
library(dplyr)
library(ggplot2)
library(patchwork)
make_plot <- function(value, .gear) {
m <- mtcars %>%
filter(cyl == cylinder[value], gear %in% .gear) %>%
group_by(gear) %>%
summarise(number = n(), average = mean(mpg), se = sd(mpg))
m %>%
mutate(gear = factor(gear, levels = unique(gear))) %>%
ggplot() +
geom_bar(aes(x = gear, y = average), stat = "identity", fill = "red") +
geom_errorbar(aes(x = gear, ymin = average - se, ymax = average + se), width = 0.2, colour = "black", alpha = 1, size = 1) +
xlab("gears") +
ylab("average mpg") +
ggtitle(paste("cylinder:", value)) +
theme(axis.ticks.x = element_blank())
}
inner_loop <- function(gear) {
# Create list
List <- lapply(seq_along(cylinder), make_plot, .gear = gear)
# Wrap plots
wrap_plots(List, nrow = 1)
}
# Outer loop
cylinder <- unique(mtcars$cyl)
gears <- unique(mtcars$gear)
# for the outer loop.
pages <- lapply(gears, inner_loop)
wrap_plots(pages, ncol = 1)