Моя цель — удлинить, изменить порядок и заполнить список графиков «пустыми» графиками. если какие-либо элементы списка отсутствуют.
До сих пор моя попытка была в состоянии удлинить и изменить порядок частичного списка, но я борюсь назначить пустые участки. Вот неполный список и желаемый результат, а также код моей попытки.
Как я могу добавить «emptyPlot» к каждому элементу NULL в «l3»? Или есть другой способ сделать это?
library(ggplot2)
somePlot <- ggplot() + ggtitle("Some plot.")+ theme_bw()
emptyPlot <- ggplot() + ggtitle("Nothing to see here.") + theme_void()
# input list
partial_list <- list(fourth = somePlot, first = somePlot)
# desired output
desired <- list(first = somePlot, second = somePlot, third = emptyPlot, fourth = somePlot)
# a reference vector for what the list should contain that also specifies the desired order
reference <- c("first", "second", "third", "fourth")
# convert missing elements to NA
reference[!reference %in% names(partial_list)] <- NA
# lengthen list with NAs
l2 <- c(partial_list, rep(NA, sum(is.na(reference))))
# reorder to follow the reference
l3 <- l2[reference]
# this approach did not give the desired output.
appendEmptyPlot <- function(x) {x[is.null(x)] <- emptyPlot; x}
l4 <- lapply(l3, appendEmptyPlot)
l4
Вероятно, вам понадобится такой цикл:
for (r in reference) {
if (!r %in% names(partial_list))
partial_list[[r]] <- emptyPlot
}
l4 <- partial_list[reference]