title: for loop in R to run function on multiple files, calculate value from output, place in new file
body: <p>I'm trying to use a for loop to run random forest on multiple input files in sequence, calculate the OOB error of the resulting rf object for each of those files (based on 5000 trees), and output those OOB error values into one results file. The results file is returning the exact same OOB values for each file, which is not correct (i.e., it's returning the OOB value for only one of my input files). I've tried the following:</p>
  
  <pre><code>fileNames = list.files(pattern="\\.csv")
  
  for(fileName in fileNames){
  
    sample = read.csv(fileName, header=TRUE, sep=",")
  
    rf_rand = randomForest(
      sample[,3:45], 
      sample$Organism, 
      proximity=TRUE,
      importance=TRUE, 
      ntree=5000)
  
    OOB = mean(rf_rand$err.rate[,1])
  
    results = data.frame(fileNames,OOB)
  
    write.table(results,"rand_oob_reps.txt",sep = "\t")     
  }
  
  results
  
  #1 sample1.csv 0.06764769
  #2 sample2.csv 0.06764769
  #3 sample3.csv 0.06764769
  </code></pre>
  
  <p>I have also tried unsuccessfully with:</p>
  
  <pre><code>for(i in 1:length(fileNames))
  </code></pre>
  
  <p>This seems like a simple issue, but so far my search for answers has come up empty. Thanks for any insights.</p>