title: Calculate r-squared between two columns for multiple files in a folder and write results to a single file using R
body: <p>I have multiple .txt files in a folder, each having multiple columns. I want to calculate r squared value between col 2 and 7 of each file and print the same into one output file. I tried following for one file and it works:</p>
  
  <pre><code>y&lt;- read.table("A4GALT_BLCA.txt", sep ="\t", header=T)
  x&lt;-lm(y[,2]~ y[,7])
  summary(x)$r.squared
  </code></pre>
  
  <p>When I try to do it for all files using apply or for loop, it doesn't work.</p>
  
  <p>with for loop:</p>
  
  <pre><code>filenames &lt;- list.files("trial", pattern="*.txt", full.names=TRUE)
  
  for (i in 1:length(filenames)) {y&lt;- read.table(filenames[i], sep ="\t", header=T) 
  + x&lt;- lm(y[,2] ~ y[,7]) 
  + out&lt;-summary(x)$r.squared
  + write.table(out, "test_out.txt", sep="\t")
  + }
  </code></pre>
  
  <p>This gives one file as output but has only one value in it (for the last file). How can i improvise it to have values from all the file. </p>
  
  <p>Thanks</p>