1

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.

tnt
  • 1,149
  • 14
  • 24

2 Answers2

2

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 
Dave2e
  • 22,192
  • 18
  • 42
  • 50
0

as.vector will convert a matrix to a vector (column-wise):

as.vector(dist)

or if you want it row-wise:

as.vector(t(dist))

If you need to keep the coordinates, one way would be:

df <- as.data.frame(dist) 
names(df) <- c("dist.1", "dist.2")
reshape(data = df, direction = "long", varying = 1:2)

Optionally, you can name the columns with coordinates:

reshape(data = df, direction = "long", varying = 1:2, timevar = "x", idvar = "y")
Jozef
  • 2,617
  • 14
  • 19