[GIS] Distance Matrix output

distance matrixqgis

I'm using QGIS 2.18 Las Palmas, and I'm trying to build up a Distance Matrix of a series of points for a Mantel test. Specifically, I have a series of points and I want to calculate the distance of each of them to all the other ones. Now, when I use the 'Distance Matrix' tool in QGIS it gives me a three column table with all the distances, in this way:

InputID,C,254 TargetID,C,254 Distance,C,254
1 1 0
1 2 16.2788206
1 3 19.92485885
1 4 36.138622
1 5 69.23149572

This kind of output file contains all the information I need, but in the wrong format. What I'm looking for is a triangular distance matrix, as I need it as an input file for a Mantel test, like this one:

    1           2           3           4           5

1 0
2 16.2788206 0
3 19.92485885 23.84674 0
4 36.138622 29.4846735 55.68871 0
5 69.23149572 45.22356 66.254128 78.6542212 0

If it is possible to do this with QGIS, how do I do it?

Best Answer

If you don't mind a programmatic solution, you can do this easily in R with the dist function and the raster library. Example:

# make sure you have the raster library - you might also need rgdal
install.packages(c('raster', 'rgdal'))

# load the raster library
library(raster)

# define file path
shpFile <- "C:/path/to/shape/file.shp"

# load shapefile
shp <- shapefile(shpFile)

# convert SpatialPointsDataFrame to data.frame
shpDF <- as.data.frame(shp)

# get the distance matrix for coordinate sets
distMat <- dist(shpDF[,2:3])

# print results
print(distMat)

          1         2         3
2 192801.33                    
3 261837.21 133653.67          
4 240095.52  60905.06  86724.96

By default it will return the euclidean distance between each point in the shapefile. This should be used for data in a projected coordinate system. If you are using a geographic coordinate system, then look into the distHaversine function in the geosphere library.

Related Question