-2

I have a dataframe as follow:

    X1      X2  
6.134811 49.58038
6.135331 49.58127
6.135670 49.58170
6.134905 49.58199

I would like to create a new variable X3 where will be computed the distance in meters between each sequence of GPS points. The 1st row can be 0, then on the second row will be the distance between 1st & 2nd row, on the 3rd row will be the distance between 2nd & 3rd row and so on, as follow:

    X1      X2      X3
6.134811 49.58038   0
6.135331 49.58127   114
6.135670 49.58170   61
6.134905 49.58199   90

Any ideas on how to solve this would be greatly appreciated!

  • 2
    These are probably latitudes and longitudes. First you need to determine how to get a distance for one pair of "points" and then you need to run these coordinates through a loop that does it repeatedly. Seems you have made very little effort on your own so far (or at least not offered any evidence of effort. Where did those X3-distances come from? – IRTFM Aug 03 '17 at 19:07
  • Is that in Luxembourg? You likely want Haversine... https://www.r-bloggers.com/great-circle-distance-calculations-in-r/ – Mark Setchell Aug 03 '17 at 19:11
  • 1
    Possible duplicate of [Calculate distance between two latitude-longitude points? (Haversine formula)](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula) – Bartosz Mikulski Aug 03 '17 at 19:20
  • I found different packages to calculate distance between 2 points like sp, geosphere etc. What I don't know is how to iterate over each 2 rows and to add the result on X3. For the moment, I added manually the distance on X3 just for demonstration purpose with some manual tools. Many thanks for you fast response! – Bogdan Toader Aug 03 '17 at 19:27

1 Answers1

1

Use head and tail to isolate the "all but first" and "all but last" parts of your data.frame, then pass those to your desired distance function. Prepend the result with 0 and assign it to a new column in your data:

X <- data.frame( X1 = c(6.134811, 6.135331, 6.135670, 6.134905),
                X2 = c(49.58038, 49.58127, 49.58170, 49.58199) )
X$X3 <- c( 0, geosphere::distCosine( head(X,-1), tail(X,-1) ) )
 #         X1       X2        X3
 # 1 6.134811 49.58038   0.00000
 # 2 6.135331 49.58127 105.94514
 # 3 6.135670 49.58170  53.75830
 # 4 6.134905 49.58199  63.95907
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74