title: Reducing Time for Nested For Loops in r
body: <p>I am attempting to extract some information from a data set that is about 178,000 lines long. I have a data frame with about 9 variables but am only using 3 of them for this portion. A very small subset of this data might look something like this:</p>
  
  <pre><code>date &lt;- as.Date(c("2016-09-17", "2016-09-14", "2016-09-17", "2016-09-13","2016-09-17"))
  idnum &lt;- c("1", "2", "1", "1", "1")
  hour &lt;- round(as.numeric(c("15.75", "16.34", "16.12", "15.53", "17.10")), digits = 2)
  
  all &lt;- data.frame(date, idnum, hour)
  </code></pre>
  
  <p>Giving this:</p>
  
  <pre><code>   date      idnum     hour
  2016-09-17     1      15.75
  2016-09-14     2      16.34
  2016-09-17     1      16.12
  2016-09-13     1      15.53
  2016-09-17     1      17.10
  </code></pre>
  
  <p>My goal is to determine the number of uses that are within an hour for each ID on each date (I called that variable close). In the end my data should look like this:</p>
  
  <pre><code>   date      idnum     hour    close
  2016-09-17     1      15.75      1
  2016-09-14     2      16.34      0
  2016-09-17     1      16.12      2
  2016-09-13     1      15.53      0
  2016-09-17     1      17.10      1
  </code></pre>
  
  <p>I have gotten the following code to work for this small data set</p>
  
  <pre><code>all$close &lt;- 0
  m &lt;- 1
  
  for (i in m:nrow(all)) {
      for (j in 1:nrow(all)) {
          if(i != j &amp; all$date[i] == all$date[j] &amp; all$idnum[i] == idnum[j] 
            &amp; abs(all$hour[i] - all$hour[j]) &lt;= 1) {
             all$close[i] &lt;- all$close[i] + 1                              
          } else {
            all$close[i] &lt;- all$close[i]
          }
      }
      m = m + 1
  }
  </code></pre>
  
  <p>However, as soon as I expand this to a larger number of rows, the run time is really long. Is there a more efficient way to do this in <code>r</code>?</p>