title: Using grep, grepl and regexpr within loops in R
body: <p>I want to automate the extraction of certain information from text files using grep, grepl and regexpr. I have a code that works when I do it for each individual file, however I cannot get the loop to work, to automate the process for all files in my working directory. </p>
  
  <p>I am reading in the txt files as strings because of the structure of the data. The loop seems to iterate through the first file numerous times corresponding to the number of files in the directory, obviously because of the <code>length(txtfiles)</code>command in the <code>for</code> statement. </p>
  
  <pre><code>txtfiles = list.files(pattern="*.txt")
  
  for (i in 1:length(txtfiles)){
  all_data &lt;- readLines(txtfiles[i])
  
  #select hours of operation 
  hours_op[i] &lt;- all_data[hours_of_operation &lt;- grep("Annual Hours of Operation:",all_data)]
  hours_op[i] &lt;-regmatches(hours_op, regexpr("[0-9]{1,9}.[0-9]{1,9}",hours_op))
  
  }
  </code></pre>
  
  <p>I would be grateful if someone could point me in the right direction to repeat this routine for each file, rather than the same file multiple times over. I want to end up with a list of the file names and the corresponding <code>hours_op</code>. </p>