How to calculate distance using longitude, and latitude ? Using distm(), How to enter multiple points?

Following is the data frame I'm using

glimpse(df_coordinates)
Rows: 3,742,202
Columns: 4

$ start_lng -87.6353, -87.6431, -87.7079, -87.6500, -87.6699, -87.6468, -~

$ start_lat 41.8777, 41.9295, 41.9296, 41.9680, 41.8715, 41.8472, 41.8715~

$ end_lng -87.6268, -87.6674, -87.7079, -87.6368, -87.6468, -87.6555, -~

$ end_lat 41.8915, 41.9671, 41.9296, 41.9367, 41.8472, 41.8695, 41.8715~

Hi,

Here is a way to compute the distance between start and endpoint for each row, is that what you need?

suppressPackageStartupMessages({
  library(geosphere)
  library(dplyr)})

coordinates<-data.frame(
  start_long=c( -87.6353, -87.6431, -87.7079, -87.6500, -87.6699, -87.6468),
  start_lat=c( 41.8777, 41.9295, 41.9296, 41.9680, 41.8715, 41.8472),
  end_long=c( -87.6268, -87.6674, -87.7079, -87.6368, -87.6468, -87.6555),
  end_lat=c( 41.8915, 41.9671, 41.9296, 41.9367, 41.8472, 41.8695))


coordinates%>%rowwise%>%
  mutate(distance=distm(x=c(start_long,start_lat),
                        y=c(end_long,end_lat)))
#> # A tibble: 6 x 5
#> # Rowwise: 
#>   start_long start_lat end_long end_lat distance[,1]
#>        <dbl>     <dbl>    <dbl>   <dbl>        <dbl>
#> 1      -87.6      41.9    -87.6    41.9        1687.
#> 2      -87.6      41.9    -87.7    42.0        4637.
#> 3      -87.7      41.9    -87.7    41.9           0 
#> 4      -87.6      42.0    -87.6    41.9        3645.
#> 5      -87.7      41.9    -87.6    41.8        3311.
#> 6      -87.6      41.8    -87.7    41.9        2580.

Created on 2021-06-12 by the reprex package (v2.0.0)

Thanks, It worked!

Sorry for being a nuisance, how can I extract distance as a vector? The distance column does not appear as variable when I ran the str() function.

str(coordinates)
'data.frame': 3742202 obs. of 4 variables:

$ Start_x.v: num -87.6 -87.6 -87.7 -87.7 -87.7 ...

$ Start_y.v: num 41.9 41.9 41.9 42 41.9 ...

$ End_x.v : num -87.6 -87.7 -87.7 -87.6 -87.6 ...

$ End_y.v : num 41.9 42 41.9 41.9 41.8 ...

That is because I did not assign the last part of the code to an object which means that the output of the operations is generated and shown but it is nowere saved.

If you run it as below, the new column will be saved in the coordinates data frame.

coordinates<-coordinates%>%rowwise%>%
  mutate(distance=distm(x=c(start_long,start_lat),
                        y=c(end_long,end_lat)))

Look up the haversine formula.

This topic was automatically closed 21 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.