-
Notifications
You must be signed in to change notification settings - Fork 1
/
GeoDistanceInMetresMatrix.R
54 lines (42 loc) · 2.37 KB
/
GeoDistanceInMetresMatrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
ReplaceLowerOrUpperTriangle <- function(m, triangle.to.replace){
# If triangle.to.replace="lower", replaces the lower triangle of a square matrix with its upper triangle.
# If triangle.to.replace="upper", replaces the upper triangle of a square matrix with its lower triangle.
if (nrow(m) != ncol(m)) stop("Supplied matrix must be square.")
if (tolower(triangle.to.replace) == "lower") tri <- lower.tri(m)
else if (tolower(triangle.to.replace) == "upper") tri <- upper.tri(m)
else stop("triangle.to.replace must be set to 'lower' or 'upper'.")
m[tri] <- t(m)[tri]
return(m)
}
GeoDistanceInMetresMatrix <- function(df.geopoints){
# Returns a matrix (M) of distances between geographic points.
# M[i,j] = M[j,i] = Distance between (df.geopoints$lat[i], df.geopoints$lon[i]) and
# (df.geopoints$lat[j], df.geopoints$lon[j]).
# The row and column names are given by df.geopoints$name.
GeoDistanceInMetres <- function(g1, g2){
# Returns a vector of distances. (But if g1$index > g2$index, returns zero.)
# The 1st value in the returned vector is the distance between g1[[1]] and g2[[1]].
# The 2nd value in the returned vector is the distance between g1[[2]] and g2[[2]]. Etc.
# Each g1[[x]] or g2[[x]] must be a list with named elements "index", "lat" and "lon".
# E.g. g1 <- list(list("index"=1, "lat"=12.1, "lon"=10.1), list("index"=3, "lat"=12.1, "lon"=13.2))
DistM <- function(g1, g2){
require("Imap")
return(ifelse(g1$index > g2$index, 0, gdist(lat.1=g1$lat, lon.1=g1$lon, lat.2=g2$lat, lon.2=g2$lon, units="m")))
}
return(mapply(DistM, g1, g2))
}
n.geopoints <- nrow(df.geopoints)
# The index column is used to ensure we only do calculations for the upper triangle of points
df.geopoints$index <- 1:n.geopoints
# Create a list of lists
list.geopoints <- by(df.geopoints[,c("index", "lat", "lon")], 1:n.geopoints, function(x){return(list(x))})
# Get a matrix of distances (in metres)
mat.distances <- ReplaceLowerOrUpperTriangle(outer(list.geopoints, list.geopoints, GeoDistanceInMetres), "lower")
# Set the row and column names
rownames(mat.distances) <- df.geopoints$name
colnames(mat.distances) <- df.geopoints$name
return(mat.distances)
}
# x <- read.csv("Dgeo_MX.csv")
# colnames(x) <- c("name", "lat", "lon")
# GeoDistanceInMetresMatrix(x)