Skip to content

Instantly share code, notes, and snippets.

@mpettis
Created June 11, 2024 19:04
Show Gist options
  • Save mpettis/34046edd4aca8ec863ee8b300cfdcb38 to your computer and use it in GitHub Desktop.
Save mpettis/34046edd4aca8ec863ee8b300cfdcb38 to your computer and use it in GitHub Desktop.
library(dplyr)
library(purrr)
library(ggplot2)
#;; Data
df <- tibble(cat=c("A", "A", "B", "B"),
x=c(1, 2, 1, 2),
y=c(1, 2, 2, 1))
#;; List of dataframes to plot
listOf_df <- df |> group_by(cat) |> group_split()
#;;-----------------------------------------------------------------------------
#;; With for loop
plotOutput_lst <- list()
for (i in length(listOf_df)) {
p <- ggplot(listOf_df[[i]]) + geom_line(aes(x=x, y=y))
plotOutput_lst[[i]] <- p
}
#;; Somehow first entry is null, so only last one has a plot.
plotOutput_lst
#;; Only shows last plot, as first one is NULL
print(plotOutput_lst[[1]])
print(plotOutput_lst[[2]])
#;;-----------------------------------------------------------------------------
#;; With for loop, with force()
#;; Still, somehow first entry is null, so only last one has a plot.
plotOutput_lst <- list()
for (i in length(listOf_df)) {
p <- ggplot(listOf_df[[i]]) + geom_line(aes(x=x, y=y))
plotOutput_lst[[i]] <- force(p)
}
plotOutput_lst
print(plotOutput_lst[[1]])
print(plotOutput_lst[[2]])
#;;-----------------------------------------------------------------------------
#;; With map(), will work as expected:
rm(plotOutput_lst)
plotOutput_lst <- map(listOf_df, ~{
p <- ggplot(.x) + geom_line(aes(x=x, y=y))
p
})
plotOutput_lst
#;; This will print both plots
print(plotOutput_lst[[1]])
print(plotOutput_lst[[2]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment