title: For-Loop to read and save multiple data files
body: <p>I would like to apply the same code to around 600 separate files. I cannot first merge all files, as individual files are already very large. I would like to open file per file, do my data manipulations, save that file, close it and go on to the next file).</p>
  
  <p>My code is the following:</p>
  
  <pre><code>#List all files from directory (this works)
  files &lt;- list.files("path", pattern="*.TXT")
  
  #Loop over files
  for(i in 1:length(files))
  {
  data[i] &lt;- read.table(files[i], header=TRUE)
  
  data[i] &lt;- merge(data[i], dataset, by.x="ID", all.x=TRUE) #dataset is a file containing IDs for observations I wish to select from each file (it has a variable 'dummy' that equals 1 for each ID i wish to subset)
  attach(data[i])
  dummy[is.na(dummy)] &lt;- 0
  
  data[i] &lt;- data[i][which(dummy==1),]
  write.table(data[i], "PATH/data[i].txt", sep="\t")
  
  rm(list=ls())
  }
  </code></pre>
  
  <p><strong>OUTPUT</strong>
  Listing all files from directory works:</p>
  
  <pre><code>&gt; print(files)
  [1] "2729_1636_1687.TXT" "2729_1688_1739.TXT"
  </code></pre>
  
  <p>The loop does not work:</p>
  
  <pre><code>Error in data[i] &lt;- read.table(files[i], header = TRUE) : 
    object of type 'closure' is not subsettable
  </code></pre>
  
  <p><strong>SOLUTION</strong></p>
  
  <pre><code>for(i in 1:length(files))
  {
  data &lt;- read.table(files[i], header=TRUE)
  
  data &lt;- merge(data, dataset, by.x="ID", all.x=TRUE) 
  dummy[is.na(dummy)] &lt;- 0
  
  data &lt;- data[which(dummy==1),]
  write.table(data, paste("PATH/data[",i,"].txt"), sep="\t")
  
  rm(data)
  }
  </code></pre>