title: Calculate distance from GPS data
body: <p>I do have data frame with gps data and I need to calculate distance between two rows (current and previous)</p>
  
  <pre><code>            id                 time       lat      long heartrate altitude
  1  20130424.tcx 2013-04-24T04:53:22Z 50.024818 14.522724       151     &lt;NA&gt;
  2  20130424.tcx 2013-04-24T04:53:26Z 50.024818 14.522724        96     &lt;NA&gt;
  3  20130424.tcx 2013-04-24T04:53:30Z 50.024818 14.522724       104     &lt;NA&gt;
  4  20130424.tcx 2013-04-24T04:53:34Z 50.024818 14.522724       107     &lt;NA&gt;
  5  20130424.tcx 2013-04-24T04:53:38Z 50.024818 14.522724       108     &lt;NA&gt;
  6  20130424.tcx 2013-04-24T04:53:42Z 50.024818 14.522724       112    372.0
  7  20130424.tcx 2013-04-24T04:53:46Z 50.024818 14.522724       151    372.0
  8  20130424.tcx 2013-04-24T04:53:47Z 50.024677 14.522874       151    356.0
  9  20130424.tcx 2013-04-24T04:53:50Z 50.024677 14.522874       118    356.0
  10 20130424.tcx 2013-04-24T04:53:54Z 50.024677 14.522874       118    356.0
  11 20130424.tcx 2013-04-24T04:53:58Z 50.024464 14.522917       147    358.0
  12 20130424.tcx 2013-04-24T04:54:02Z 50.024464 14.522917       144    358.0
  13 20130424.tcx 2013-04-24T04:54:06Z 50.024269 14.522853       150    367.0
  14 20130424.tcx 2013-04-24T04:54:10Z 50.024269 14.522853       152    367.0
  15 20130424.tcx 2013-04-24T04:54:13Z 50.024002 14.522874       152    380.0
  </code></pre>
  
  <p>I am able to join data to itself and get previous row for each row (there might be easier solution):</p>
  
  <pre><code>library(sqldf)
  mydft    = mydf[-nrow(mydf),] 
  mydft$id  = seq_along(mydft$id) +1
  mydf$id  = seq_along(mydf$id)
  mydft2 &lt;- sqldf("select a.*, b.lat as lat2, b.long as long2 from mydf a left join mydft b using (id)")
  </code></pre>
  
  <p>How can I now calculate distance from columns <code>lat, long, lat2, long2</code> ? I've tried approach described <a href="http://www.r-bloggers.com/great-circle-distance-calculations-in-r/" rel="nofollow">here</a>:</p>
  
  <pre><code>R &lt;- 6371 # Earth mean radius [km]
  mydft2$delta.long &lt;- (mydft2$long2 - mydft2$long)
  mydft2$delta.lat &lt;- (mydft2$lat2 - mydft2$lat)
  mydft2$a &lt;- sin(mydft2$delta.lat/2)^2 + cos(mydft2$lat) * cos(mydft2$lat2) * sin(mydft2$delta.long/2)^2
  mydft2$c &lt;- 2 * asin(min(1,sqrt(mydft2$a)))
  mydft2$d = R * c
  </code></pre>
  
  <p>But this retuns only list NAs.</p>