title: How to select files in a directory according to specific string in filename?
body: <p>I'm reading some netcdf files from a directory into R. The netcdf files are names according to some specific feature of the data.</p>
  
  <p>Here is an example:</p>
  
  <pre><code>aa &lt;- c("dayavg_fcst_surf125.011_tmp.1962010100_1962123121.nc",
          "dayavg_fcst_surf125.011_tmp.1972010100_1972123121.nc",
          "dayavg_fcst_surf125.011_tmp.1982010100_1982123121.nc",
          "dayavg_fcst_surf125.011_tmp.1992010100_1992123121.nc",
          "dayavg_fcst_surf125.011_tmp.2002010100_2002123121.nc",
          "dayavg_fcst_surf125.011_tmp.2010010100_2010123121.nc",
          "dayavg_fcst_surf125.011_tmp.2012010100_2012123121.nc",
          "dayavg_fcst_surf125.011_tmp.2014020100_2014022821.nc",
          "dayavg_fcst_surf125.011_tmp.2014120100_2014123121.nc",
          "dayavg_fcst_surf125.011_tmp.2015020100_2015022821.nc")
  </code></pre>
  
  <p>These were collected using the list.files function.</p>
  
  <p>I would like to select (keep) a subset of these filenames (as strings), specifically the files that refer to the data collected in 2010 and 2014. </p>
  
  <p>The year is indicated in the filenames following the '.tmp' string. For example, the first entry would be the year 1962, and so on.</p>
  
  <p>To achieve this, I have tried the following:</p>
  
  <pre><code>iyears &lt;- c(2010,2014)
  ll &lt;- list()
  for (i in 1:length(iyears)){
    ll[[i]] &lt;- aa[grepl(iyears[i],aa)]
  }
  ll &lt;- c(ll[[1]],ll[[2]])
  </code></pre>
  
  <p>which returns:</p>
  
  <pre><code>&gt; ll
   [1] "dayavg_fcst_surf125.011_tmp.1962010100_1962123121.nc" "dayavg_fcst_surf125.011_tmp.1972010100_1972123121.nc"
   [3] "dayavg_fcst_surf125.011_tmp.1982010100_1982123121.nc" "dayavg_fcst_surf125.011_tmp.1992010100_1992123121.nc"
   [5] "dayavg_fcst_surf125.011_tmp.2002010100_2002123121.nc" "dayavg_fcst_surf125.011_tmp.2010010100_2010123121.nc"
   [7] "dayavg_fcst_surf125.011_tmp.2012010100_2012123121.nc" "dayavg_fcst_surf125.011_tmp.2014020100_2014022821.nc"
   [9] "dayavg_fcst_surf125.011_tmp.2014120100_2014123121.nc" "dayavg_fcst_surf125.011_tmp.2015020100_2015022821.nc"
  [11] "dayavg_fcst_surf125.011_tmp.2014020100_2014022821.nc" "dayavg_fcst_surf125.011_tmp.2014120100_2014123121.nc"
  </code></pre>
  
  <p>whereas the answer should be:</p>
  
  <pre><code>&gt; ll
  [1] "dayavg_fcst_surf125.011_tmp.2010010100_2010123121.nc" "dayavg_fcst_surf125.011_tmp.2014020100_2014022821.nc"
  [3] "dayavg_fcst_surf125.011_tmp.2014120100_2014123121.nc"
  </code></pre>
  
  <p>The problem is that the date string in the file name is as follows:</p>
  
  <p>yyyymmddhh</p>
  
  <p>so, 2010 also appears in </p>
  
  <p>"dayavg_fcst_surf125.011_tmp.1982010100_1982123121.nc",</p>
  
  <p>due to 198[2 01 0]1.</p>
  
  <p>Can anyone suggest a method of obtaining the desired result?</p>