1

I have a series of txt files I would like to plot in R, but I need help constructing a for loop to automate this for when I have dozens of files.

My current script, which is fine for a few files, is simply this two-line repetitive code:

data <- read.table("/path/filename1.txt")
    plot(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data2 <- read.table("/path/filename2.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data3 <- read.table("/path/filename3.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data3 <- read.table("/path/filename3.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

I am certain there is a simpler way to do this using a for loop, but I am unfamiliar with R and not sure how to accomplish this.

Thank you for the help!

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • This is pretty close to a [duplicate question](https://stackoverflow.com/questions/19852774/how-to-automatically-plot-many-csv-files-with-the-same-number-of-rows-and-column) and [this question](https://stackoverflow.com/questions/7311372/merging-data-from-many-files-and-plot-them/7311591) also, and [this one](https://stackoverflow.com/questions/18826985/open-and-plot-multiple-files). – lmo Apr 16 '18 at 16:55

2 Answers2

2

Since I don't have your files, this code is not tested, but it could work.

First set your working directory and then apply the following....

Read all files

Files <- lapply(list.files(pattern = "\\.txt$"), read.table)

Plot them..

lapply(Files, function(x) points(x, type = 'l', ylim=c(0,100), xlim = c(350,900)))
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

You can do so using a for loop as you suggested, like so:

files <- c('/path/filename1.txt', '/path/filename2.txt')

for(file in files)
{
  data <- read.table(file)
  plot(data, type = 'l', ylim=c(0,100), xlim = c(350,900))
}

In this case, you are storing your file paths in a vector called files, and then performing the same action on each individual member of files.

93i7hdjb
  • 1,136
  • 1
  • 9
  • 15