0

I'm new to R and want to automatize plotting of my data. I wrote a small script for this that should do the following things:

1) Iterates over csv-files in a given path and stores data in a list of dataframes

2) Iterates over this list, uses ggplot to plot every single dataframe within this list and stores result in variable.

#loading libraries#

library(ggplot2)
library(forcats)
library(magrittr) 


#setting wd#
#creating list#
#listing files in given path#

setwd("/path/to/csvfiles")
mylist <- list()
filenames <- list.files(path=getwd())


#iterating over csv-files#
#storing input in variables (var_1,...var_n) and in "mylist"#
#change decimal comma to dot#


for (i in (1:length(filenames))){

  mylist[[i]] <- assign(paste("var",i, sep="_"), read.csv(filenames[i])[ ,1:2]) %>%
    sapply(gsub, pattern=",", replacement=".") %>%
    as.data.frame()
}


#Iterate over list, plotting single element of list and save in variables (plot_1,...,plot_n) in order to later plot them in a given frame (e.g. by using multiplot)#

for (k in 1:length(mylist)){
    mylist[[k]]$value <- as.numeric(as.character(mylist[[k]]$value))

     assign(paste("plot",k, sep="_"),
           ((ggplot(mylist[[k]], aes(x=mylist[[k]]$column1, y=mylist[[k]]$value))) + 
             aes(x = fct_inorder(column1)) +
             ggtitle(paste("plot",k,sep="")) + 
             geom_boxplot(outlier.shape = NA)))
}

I end up with the actual number of plots I expect from n different files (--> n plots). All of them have the corresponding title (e.g. variable plot_1 also has the title "plot_1", ...).

However, all of the plots look the same. I checked it in detail and figured out that this data is actually representing the last element of the list, assuming that the other elements of the list are not plotted and saved properly into the variable (although iterating over theme title obviously works...). When I plot manually for a given element of list, it works perfectly, but within the loop the mentioned problems appear.

Probably it's something really obvious but I can't figure it out. Thank you for your help!

intollo90
  • 1
  • 1
  • Possible duplicate of [Storing ggplot objects in a list from within loop in R](https://stackoverflow.com/questions/31993704/storing-ggplot-objects-in-a-list-from-within-loop-in-r) – Geochem B Jul 19 '17 at 16:25
  • There is a very similar question already answered on stack. https://stackoverflow.com/questions/31993704/storing-ggplot-objects-in-a-list-from-within-loop-in-r – Geochem B Jul 19 '17 at 16:24
  • What is the point of the 2nd `aes`? in `(ggplot(mylist[[k]], aes(x=mylist[[k]]$column1, y=mylist[[k]]$value))) + aes(x = fct_inorder(column1))` – CPak Jul 20 '17 at 04:04

0 Answers0