1

I am trying to write an R script using for loop to perform statistical analyses and to produce plots for each file.

my files ends with .txt Here is my script but it requires improvement as below.

files <- list.files(path="/Users/MD/Desktop/Files/", pattern="*.txt")
for (i in files){
  i_automean <- mean(i[1:5651,10])
  i_xmean <- mean(i[5652:7977,10])
  barplot(i[,10]/i_automean, ylim = c(0,2.5))
  abline(h=1, col ="red", lwd =3)
  abline(h=22.06126/i_automean, col ="red", lwd =3)
  abline(v=2300*1.2, col="blue", lwd =3)
  abline(v=5651*1.2, col="blue", lwd=3)
  pdf(i.pdf, "/Users/MD/Desktop/Files/");
  dev.off()
} 

Error in i[1:5651, 10] : incorrect number of dimensions

When I run each command one by one for each file, I don't receive error:

Commands that I run one by one are:

File1 <- read.table(file = "/Users/MD/Desktop/Files/File1.txt")
File1
File1_automean <- mean(File1[1:5651,10])
File1_automean
File1_Xmean <- mean(File1[5652:7977,10])
File1_Xmean
barplot(File1[,10]/18.02876, ylim = c(0,2.5))
abline(h=1, col ="red", lwd =3)
abline(h=22.06126/18.02876, col ="red", lwd =3)
abline(v=2300*1.2, col="blue", lwd =3)
abline(v=5651*1.2, col="blue", lwd=3)

Note: 18.02876 is File1_automean result.

  • Maybe I'm wrong, but I think you forget to load the file in your first chunk of code, you should add `i = read.table(file = i)` before `automean` part. For now, i is a character vector. But, if load your file as `i`, I bet you will have some issues with the naming part at the end. – dc37 Nov 13 '19 at 16:54
  • I add an answer with a proposed revision of your code. – dc37 Nov 13 '19 at 17:03

1 Answers1

0

What do you think about this solution ?

files <- list.files(path="/Users/MD/Desktop/Files/", pattern="*.txt")
setwd("/Users/MD/Desktop/Files")
for (j in 1:length(files)){
  i <- read.table(files[j])
  i_automean <- mean(i[1:5651,10])
  i_xmean <- mean(i[5652:7977,10])
  barplot(i[,10]/i_automean, ylim = c(0,2.5))
  abline(h=1, col ="red", lwd =3)
  abline(h=22.06126/i_automean, col ="red", lwd =3)
  abline(v=2300*1.2, col="blue", lwd =3)
  abline(v=5651*1.2, col="blue", lwd=3)
  pdf(paste0(files[j],".pdf"))
  graphics.off()
} 
dc37
  • 15,840
  • 4
  • 15
  • 32
  • One thing I need is to open pdf files and reduce their size, because it says figure margins are too big. Pdf files can't open. – user12367991 Nov 13 '19 at 17:15
  • @user12367991, in the Rstudio console, try to run `dev.off` several times (it will force to reset the graphic device in rstudio (https://support.rstudio.com/hc/en-us/articles/200488548-Problem-with-Plots-or-Graphics-Device). I will also edit my code to use `graphics.off()` instead which is (I think) more appropriate for running script. Otherwise, it can be dependent of Rstudio, maybe you can try to run this script directly in R terminal. More discussion here: (https://stackoverflow.com/questions/12766166/error-in-plot-new-figure-margins-too-large-in-r) – dc37 Nov 13 '19 at 17:21