title: How to speed up nested loops in R
body: <p>I have 2 data.frames: </p>
  
  <ol>
  <li><em>users</em> that contains longitude and latitude of every user</li>
  <li><em>stops</em> that contains longitude and latitude of every bus stop</li>
  </ol>
  
  <p>I would like to calculate % of users that have at least 1 bus stop in specific radius (meters). </p>
  
  <p>So I created a function with nested loop to iterate through each user and break as long as there is 1 stop in desired radius.</p>
  
  <p>The solution works, the problem is performance. Is there a way to speed it up?</p>
  
  <pre><code>percentage_of_users_near_to_busstop &lt;- function(users, stops, radius) {
     users$stops_in_radius &lt;- 0
     users_length &lt;- nrow(users)
     stops_length &lt;- nrow(stops)
     for (i in 1:users_length) {
        for (j in 1:stops_length) {
           if ( distm (c(users$longitude[i], users$latitude[i]), 
                   c(stops$longitude[j], stops$latitude[j]), 
                   fun = distHaversine) &lt; radius)
           { users[i, "stops_in_radius"] &lt;- users[i, "stops_in_radius"] + 1
           break }
        }
        #print(paste0(i/users_length*100, "%"))
     }
     return(nrow(subset(users, stops_in_radius &gt; 0))/nrow(users))
  }
  </code></pre>