title: Calculate the distance between two coordinates columns group by individuals of different ID length in R
body: <p>I have locations of individuals, and the dataframe is like:</p>
  
  <pre><code> ID       Lat       Lon        Distance
   1        51.5184   -0.1382
   1        51.5147   -0.1532
   2        51.5184   -0.1342
   2        51.5147   -0.1522
   2        51.5537   -0.1556
   ...      ...       ...
  </code></pre>
  
  <p>and I would like to calculate the moving distance of each individual. I am not very sure how to calculate the distances of points group by individuals in a dataframe. </p>
  
  <p>I know there are some similar questions that posted before, such as this: <a href="https://stackoverflow.com/questions/47115848/how-can-i-calculate-the-distance-between-latitude-and-longitude-along-rows-of-co,but">How can I calculate the distance between latitude and longitude along rows of columns in R?</a> I found our situation is a little different. When I used this function: </p>
  
  <p><code>mutate(Distance = 
                    c(NA, distHaversine(cbind(Lon[-n()], Lat[-n()]),
                    cbind(Lon[-1], Lat[-1]))))</code> </p>
  
  <p>in my work, I found the error <code>subscript out of bounds</code>, and it means the ID are not of the same length. Just like my data shows, I have 2 ID:1 and 3 ID:2, which leads to this problem. I would really appreciate it if someone can tell me how to revise this function to fit my situation. Thanks.</p>