Search code examples
rgeosphere

get distm results in column rather than matrix


I'm trying to calculate the distance between two different sets of locations (145 in total), but the output is a matrix, rather than a column of the values.

my dataframe looks as follows:

head(df)
  site1   Lon1          Lat1      site2         lon2      lat2
1   TN    -64.33788     45.90501  BennettMeadow  -72.47   42.68
3   TN    -64.33788     45.90501   45.91:-64.34  -64.34   45.91
4   TN    -64.33788     45.90501    45.9:-64.36  -64.36   45.90
5   TN    -64.33788     45.90501   45.91:-64.35  -64.35   45.91
6   TN    -64.33788     45.90501   45.89:-64.34  -64.34   45.89
7   TN    -64.33788     45.90501    45.9:-64.32  -64.32   45.90

I'm using distm for my calculations, but the output is a matrix, rather than a vector with 145 values (one for each paired set of coordinates).

dist <- distm(df[2:3], df[5:6], fun = distGeo)

head(dist[,1:5])
         [,1]     [,2]     [,3]     [,4]     [,5]
[1,] 740870.5 578.1295 1804.444 1091.421 1676.753
[2,] 740870.5 578.1295 1804.444 1091.421 1676.753
[3,] 740870.5 578.1295 1804.444 1091.421 1676.753
[4,] 740870.5 578.1295 1804.444 1091.421 1676.753
[5,] 740870.5 578.1295 1804.444 1091.421 1676.753
[6,] 740870.5 578.1295 1804.444 1091.421 1676.753

EDIT:

Looks like diag(dist) will do the trick.


Solution

  • I think you want the distGeo function and not distm function.

    The distGeo function will find the distance between each pair of points in the two vectors thus a vector result.
    The distm function will calculate the distance between every element in the first vector with every element in the second vector resulting in a "m by n" matrix.

    distGeo(df[,2:3], df[,5:6])
    #[1] 740870.5772    578.5153   1804.5629   1091.7911   1676.4440   1495.0507
    
    
    distm(df[2:3], df[5:6], fun = distGeo)
    #         [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
    #[1,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051
    #[2,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051
    #[3,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051
    #[4,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051
    #[5,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051
    #[6,] 740870.6 578.5153 1804.563 1091.791 1676.444 1495.051