I want to find the most efficient (fastest) method to calculate the distances between pairs of lat long coordinates.
A not so efficient solution has been presented (here) using sapply
and spDistsN1{sp}
. I believe this could be made much faster if one would use spDistsN1{sp}
inside data.table
with the :=
operator but I haven't been able to do that. Any suggestions?
Here is a reproducible example:
# load libraries
library(data.table)
library(dplyr)
library(sp)
library(rgeos)
library(UScensus2000tract)
# load data and create an Origin-Destination matrix
data("oregon.tract")
# get centroids as a data.frame
centroids <- as.data.frame(gCentroid(oregon.tract,byid=TRUE))
# Convert row names into first column
setDT(centroids, keep.rownames = TRUE)[]
# create Origin-destination matrix
orig <- centroids[1:754, ]
dest <- centroids[2:755, ]
odmatrix <- bind_cols(orig,dest)
colnames(odmatrix) <- c("origi_id", "long_orig", "lat_orig", "dest_id", "long_dest", "lat_dest")
My failed attempt using data.table
odmatrix[ , dist_km := spDistsN1(as.matrix(long_orig, lat_orig), as.matrix(long_dest, lat_dest), longlat=T)]
Here is a solution that works (but probably less efficiently)
odmatrix$dist_km <- sapply(1:nrow(odmatrix),function(i)
spDistsN1(as.matrix(odmatrix[i,2:3]),as.matrix(odmatrix[i,5:6]),longlat=T))
head(odmatrix)
> origi_id long_orig lat_orig dest_id long_dest lat_dest dist_km
> (chr) (dbl) (dbl) (chr) (dbl) (dbl) (dbl)
> 1 oregon_0 -123.51 45.982 oregon_1 -123.67 46.113 19.0909
> 2 oregon_1 -123.67 46.113 oregon_2 -123.95 46.179 22.1689
> 3 oregon_2 -123.95 46.179 oregon_3 -123.79 46.187 11.9014
> 4 oregon_3 -123.79 46.187 oregon_4 -123.83 46.181 3.2123
> 5 oregon_4 -123.83 46.181 oregon_5 -123.85 46.182 1.4054
> 6 oregon_5 -123.85 46.182 oregon_6 -123.18 46.066 53.0709
spDistsN1
. You should rewrite your own function that doesn't require converting to a matrix, since I bet that's where most of the time is. – Chirr