USAL
USAL

Reputation: 53

saving plots with the name of folder plus files names

I have this code to plot the data from a directory which contains different folders of data files. So far, with this code I can generate the graphs and can save it inside each of folder where the datafile belongs. Problem with this code is it save only one file (no matter how many datafiles I have in one folder.) Secondly, I want to save the plots with the name of the folder plus name of file, like foldername-filename.png. Code:

setwd("working directory")
folders <- list.dirs(full.names = TRUE)

lapply(folders[-1], function(dir){
  files <- list.files(dir, pattern="*.csv", full.names=TRUE, recursive=FALSE)

 lapply(files, function (file) {

  t <- read.csv(file, header=T)

#some plotng function

P1<- ggplot(df, aes(Time, Date, fill =reading)) + geom_tile(colour = "grey") + scale_fill_gradientn(colours=c("darkblue", "red", "yellow"),   values=rescale(c(0, 1000, 2000)),  guide="colorbar")+scale_x_discrete(breaks = lab1)

  ggsave(P1, filename = paste(dir, paste0("plot.jpeg"), sep = "/"))

  })
 })

I have one solution but it is giving me one error, just wondering if we have another option of doing it. Many thanks!

Upvotes: 0

Views: 1797

Answers (1)

takje
takje

Reputation: 2800

R probably does write n jpegs in the folder, where n is the number of csvs. However, since they are all named the same he just overwrites them. Try changing the ggsave command to:

ggsave(P1, filename = paste(dir, paste0("plot_",gsub('.csv','',file),".jpeg"), sep = "/"))

Where the gsub command replaces the .csv by nothing (to only include the filename).

Furthermore, you might want to do a check on the items in the folder. Maybe some of them are no csv files. A nice way to do this is by using grepl:

files <- c('a.csv','b.Rdata')
grepl('.csv$',files)
files_csv <- files[grepl('.csv$',files)]

Maybe try to include the error message in your question. Without the error, it is much harder to guess what goes wrong.

Upvotes: 1

Related Questions