Reputation: 31
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!
Upvotes: 1
Views: 100
Reputation: 61214
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)))
Upvotes: 2
Reputation: 1196
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
.
Upvotes: 0