Mollan Mollan - 1 year ago 68
R Question

Batch multiple plots in R

Good evening,

I am trying to make an R script which generates one different plot from every .txt file, which has been previously generated in batch by an instrument, and located in the same folder of the script.

I am very inexpert in R and programming in general (1-2 months of practise so far).

The .txt files have two columns each, V1 and V2, with no header.

Here is the code that I have generated:


fileNames <- list.files(getwd(), full.names = T, pattern="txt")

Speed_selection <- grep('speed', fileNames, value=TRUE)

length <- length(Speed_selection)

i <- 1

Speed <- read.table((Speed_selection[i]), header=F, sep="")

p <- ggplot(Speed)+geom_line(aes(V1,V2))
ggsave("plot.pdf", p)

} else {

My thoughts before generating the code were the following:

  • I obtain the list of all txt files in a folder. I check the list, and it prints only the txt files.

  • I select only the .txt files that have "speed" in the name.

  • I assign the value of 1 to i

  • The if loop: if i is <= than the number of the selected files

    • read the i^th file in the file selection (with i = 1, first file)

    • I make the plot I save it the directory

    • I increase i by 1.

So the next round will start with i = 2

The problem is, I only get one plot (corresponding to the first file), as the loop is not going through all the length of the "Speed_selection".

What am I doing wrong?

Thank you for the help,

best regards.

Answer Source

Here's an approach using a helper function and purrr since you're already using tidyverse.


print_plots <- function(x) {

  data <- read.table(x, header=F, sep="")

  file_name <- sprintf("%s plot.pdf", basename(x))

   p <- ggplot(data) + 

  ggsave(file_name, p)


fileNames <- list.files(getwd(), full.names = T, pattern="txt")

Speed_selection <- grep('speed', fileNames, value = TRUE)

walk(Speed_selection, ~print_plots(.x))

Or in a pipe:

list.files(getwd(), full.names = T, pattern="txt") %>%
       grep('speed', ., value = TRUE) %>%
       walk(Speed_selection, ~print_plots(.x))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download