Created
June 11, 2024 19:04
-
-
Save mpettis/34046edd4aca8ec863ee8b300cfdcb38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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