Calculate distance between a start point an end point

Hello!
I'm trying to calculate the distance between a start point and end point. I tried with geosphere package with distHaversine() function, but I don't know how to combinane longitude and latidudes that are in different columns of my dataframe. May you help me? I'm new in R programming.

Here a reproducible example of my dataframe:

coordinates <- data.frame(start_lng = c(-87.65650, -87.63193, -87.63193) , start_lat = c(41.86125, 41.87817, 41.87817), end_lng = c(-87.64117, -87.64117, -87.64117), end_lat = c(41.88338, 41.88338, 41.88338))

Thanks in advance!
Ester

I have not used that function, but looking at the documentation, something like this should work.

coordinates <- data.frame(start_lng = c(-87.65650, -87.63193, -87.63193), 
                           start_lat = c(41.86125, 41.87817, 41.87817), 
                           end_lng = c(-87.64117, -87.64117, -87.64117), 
                           end_lat = c(41.88338, 41.88338, 41.88338))
coordMat <- as.matrix(coordinates)
coordMat
     start_lng start_lat   end_lng  end_lat
[1,] -87.65650  41.86125 -87.64117 41.88338
[2,] -87.63193  41.87817 -87.64117 41.88338
[3,] -87.63193  41.87817 -87.64117 41.88338
StartMat <- coordMat[,1:2]
EndMat <- coordMat[,3:4]
Distances <- distHaversine(p1 = StartMat, p2 = EndMat) 

Thank you for your help! Could you please tell me how to change the code if I don't want to list all the values within the vectors? Beacause in reality, my dataframe has millions of rows (thus millions of coordinates).
Thank you!

coordinates <- data.frame(start_lng = c(-87.65650, -87.63193, -87.63193), 
                           start_lat = c(41.86125, 41.87817, 41.87817), 
                           end_lng = c(-87.64117, -87.64117, -87.64117), 
                           end_lat = c(41.88338, 41.88338, 41.88338))
coordMat <- as.matrix(coordinates)
StartMat <- coordMat[,1:2]
EndMat <- coordMat[,3:4]
Distances <- distHaversine(p1 = StartMat, p2 = EndMat)

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.