5

I am trying to plot graphs by loop.

Input data: Tables, which have the same ending *depth.txt, there are 2 tab delimited columns in the table:

Baba"\t"58.38

Tata"\t"68.38

Mama"\t"30.80

jaja"\t"88.65

OUTPUT: I would like to get a jpeg file with plot() for each *depth.txt (their names will be the same as the tables' names) for all files (axis x will be the first column from the table and axis y will be second column)

I created a part of the script, but it doesn't work:

files <- list.files(path="/home/fil/Desktop/", pattern="*depth.txt", full.names=T,recursive=FALSE)

for (i in 1:length(files))
plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
dev.copy(jpeg,filename=files[i])
dev.off

It doesn't work, could you help me please? I am a beginner with R.

3
  • 1
    Try including the loop-body in { ... }. Commented Aug 17, 2015 at 10:52
  • I tried it, it is good idea, but still time I am receiving only one .jpeg, with two graphs (first one is Ok, but second is with wrong values) and the name of jpeg is wrong too :-( Commented Aug 17, 2015 at 11:00
  • Strange - I have tried something like this as well some time ago and it didn't work either. Looking forward to the solution. Back then, I just used par(mfrow=c(3,4)) (which if put before the loop, will plot all the graphs on one page, 3 horizontally and 4 vertically) and then saved the whole plot in the end... Commented Aug 17, 2015 at 12:25

3 Answers 3

3

Will the following do what you want?

for (i in 1:length(files)) {
  dat <- read.table(files[i], header = FALSE, sep = '\t')
  jpeg(file = paste(files[i], '.jpeg', sep = ''))
  plot(dat$V1, dat$V2)
  dev.off()
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, it works but it rewrite my .txt file, but it is my fault with explanation of output. Is it possible to create graph without overwrite? Thank you for the working script. I saw I was close, but how I said I am beginner in R :-( Thank you so much..
Dear Lars, thank you for this great help. It is works only missing one ) , but it is not mistake. Thanks a lot
1

Similar to the first two but changing the file name for the plots

files <- paste("fil",1:3,"depth.txt",sep="")      #  example file names
for( i in 1:length(files))  {
     filename <-  sub(".txt",".jpg",files[i])
     jpeg(file=filename)
     plot(1:(10*i))                             # example plots
     dev.off()
}

Comments

0

renameing the file?

for (i in 1:length(files)) {
    file = files[i]
    file = paste("jpg",file,sep="_")
    jpeg(file)
    plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
   dev.off()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.