'Add plot to list using a for loop


Problem

I am creating a boxplot of 14 water chemistry elements. Each element has a different dataframe. I have create a for loop to loop through each data frame and plot the appropriate graph. I want to add each of the plots to a list of plots that I have created outside of the for loop.


Working Code

# Libraries
library(dplyr)
library(ggplot2)
library(readr)

# read in all files
myFiles <- list.files(pattern= ".csv")

# create a list of all 14 data frames
dataList <- list()
for (var in myFiles) {
  filepath <- file.path(paste(var))
  dataList[[var]] <- read.csv(filepath, sep=",", header=T)
}


# Plot the data as a boxplot
for (data in dataList){
  p <-
    data %>%
      ggplot(aes_string(x='Month', y=data[,5])) +
      geom_boxplot() + 
      theme_classic() +
      labs(y= colnames(data[5])) +
      scale_x_discrete
  print(p)
}

Attempts

Attempt 1:

# Plot the data and add to list
bplot_list <- list()
for (data in dataList){
  plot_list[[data]] <-
    data %>%
      ggplot(aes_string(x='Month', y=data[,5])) +
      geom_boxplot() + 
      theme_classic() +
      labs(y= colnames(data[5])) +
      scale_x_discrete
}

Attempt 2:

# Plot the data and add to list
bplot_list <- list()
for (data in dataList){
  p <-
    data %>%
      ggplot(aes_string(x='Month', y=data[,5])) +
      geom_boxplot() + 
      theme_classic() +
      labs(y= colnames(data[5])) +
      scale_x_discrete
  bplot_list[[]] <- p
}


Solution 1:[1]

This is the solution I came up with. I created a name for the graph based off the column name and used this to add to the list.

# Plot the data and add to list
bplot_list <- list()
for (data in dataList){
  chemElement <- colnames(data[5])
  p <-
    data %>%
      ggplot(aes_string(x='Month', y=data[,5])) +
      geom_boxplot() + 
      theme_classic() +
      labs(y= chemElement) +
      scale_x_discrete()
  bplot_list[[chemElement]] <- p

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Melanie Baker