I'm generating and plotting multiple ggplots based on data from two lists, therefore I'm using mapply
. One of the lists has named elements, which I would like to use as ggtitle
. But it only takes the first element for all the plots
> names(sample_subset_list)
[1] "water after day 43 dna min reads per OTU 5"
[2] "biofilm after day 43 dna min reads per OTU 5"
[3] "water after day 43 cdna min reads per OTU 5"
[4] "biofilm after day 43 cdna min reads per OTU 5"
[5] "water after day 44 dna min reads per OTU 5"
[6] "biofilm after day 44 dna min reads per OTU 5"
[7] "water after day 44 cdna min reads per OTU 5"
[8] "biofilm after day 44 cdna min reads per OTU 5"
and this is the plotting function:
ordination_plots <- list()
counter <- 0
ordination_plots <- mapply(function(x,y,counter) {
counter <- counter + 1
plot_ordination(x, y, type = "sample") +
ggtitle(names(sample_subset_list)[counter]) +
}, x = sample_subset_list, y = ordination_nmds, counter = 0, SIMPLIFY = FALSE)
this will give me plots where the title is always the first element of
names(sample_subset_list)
.
The same happens calling ggtitle(names(sample_subset_list)[]) +
If I use counter <<-
(suggested here: Using a counter inside an apply structured loop in R) or call ggtitle like
ggtitle(names(sample_subset_list)) +
or
ggtitle(names(sample_subset_list)[[]]) +
I get no title at all.
I started without a counter, which also gave me the same title for all plots. Could someone explain to me how I can iterate over the names of the list elements to use them for the ggplots?