Skip to content

Instantly share code, notes, and snippets.

@eipi10
Forked from bschneidr/extract_plots_from_list.R
Created April 18, 2019 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eipi10/f80d32cde309c7be755d165bf82d447d to your computer and use it in GitHub Desktop.
Save eipi10/f80d32cde309c7be755d165bf82d447d to your computer and use it in GitHub Desktop.
Extract all of the ggplot2 plots from a list (including sub-lists)
#' @title Extract ggplot2 plots from a list
#' @description Takes a list (potentially containing sublists) and extracts all of the ggplot2 'plot-type' objects from that list into a simple list of 'plot-type' objects.
#' @param x A list object, potentially containing sublists.
#' @return Returns a 'flat', single-level list of all the ggplot2 'plot-type' objects from within `x`, reaching recursively into sub-lists as needed. If there are no 'plot-type' objects, returns an empty list.
#' @note Whether an object is a ggplot2 'plot-type' object is defined here as an object with classes 'gg', 'gTree', or 'gtable'.
#' @export
#' @examples
#'
#' library(ggplot2)
#'
#' # Create a list of lists, containing multiple plots
#' generic_plot <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg))
#'
#' summary_plots <- list()
#' summary_plots$Demographics$Socioeconomic$Income <- generic_plot
#' summary_plots$Demographics$Socioeconomic$Education <- generic_plot
#' summary_plots$Demographics$Age <- generic_plot
#' summary_plots$Product_Usage$Purchase_Frequency <- generic_plot
#'
#' # Call the extraction function
#' extract_plots_from_list(summary_plots)
#'
extract_plots_from_list <- function(x) {
if (!is.list(x)) {
stop("`x` must be a list.")
}
if (length(x) < 1) {
return(x)
}
more_lists <- sapply(x, function(object_to_check) {
'list' %in% class(object_to_check) & !(any(c('gg', "gTree", "gtable") %in% class(object_to_check)))
})
result <- c(x[!more_lists],
unlist(x[more_lists],
recursive = FALSE))
if (sum(more_lists)) {
Recall(result)
} else {
is_plot_obj <- sapply(result, function(result_object) {
any(c('gg', "gTree", "gtable") %in% class(result_object))
})
result <- result[is_plot_obj]
return(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment