Skip to content

Instantly share code, notes, and snippets.

@alvincyh
Last active January 16, 2017 06:23
Show Gist options
  • Save alvincyh/9cd439c1377a08ab662d1fbf1cd8f3ca to your computer and use it in GitHub Desktop.
Save alvincyh/9cd439c1377a08ab662d1fbf1cd8f3ca to your computer and use it in GitHub Desktop.
Haversine distance between ODPostalCodes
---
title: "Haversine distance between ODPostalcodes"
output:
html_notebook: default
html_document: default
---
```{r}
require("dplyr")
postalcodes <- read.csv(file.choose(), stringsAsFactors = FALSE, header=TRUE)
head(postalcodes)
```
```{r}
dropcol <- c("oid")
postalcodes <- postalcodes[, ! names(postalcodes) %in% dropcol, drop = FALSE]
names(postalcodes)[names(postalcodes) == "postalcode"] <- "destination"
head(postalcodes)
```
```{r}
input <- read.table(file.choose(), sep="\t", stringsAsFactors = FALSE, header=TRUE)
head(input)
```
```{r}
dropcol <- c("id","raw")
input <- input[, ! names(input) %in% dropcol, drop = FALSE]
head(input)
```
```{r}
merged <- left_join(input, postalcodes, by="destination")
head(merged)
```
```{r}
names(merged)[names(merged) == "lon"] <- "destination.lon"
names(merged)[names(merged) == "lat"] <- "destination.lat"
head(merged)
```
```{r}
names(postalcodes)[names(postalcodes) == "destination"] <- "origin"
head(postalcodes)
```
```{r}
merged <- left_join(merged, postalcodes, by="origin")
head(merged)
```
```{r}
names(merged)[names(merged) == "lon"] <- "origin.lon"
names(merged)[names(merged) == "lat"] <- "origin.lat"
head(merged)
```
```{r}
library(geosphere)
myfn <- function(a,b,c,d) distHaversine(c(a,b),c(c,d))
merged$dist <- mapply(myfn, merged$origin.lon, merged$origin.lat, merged$destination.lon, merged$destination.lat)
# Inferior implementation with a "for loop""
# for(i in 1:dim(merged)[1]) {
# subset <- merged %>% slice(i)
# merged$dist[i] <- distHaversine(
# c(subset$origin.lon, subset$origin.lat),
# c(subset$destination.lon, subset$destination.lat)
# )
# }
head(merged)
```
```{r}
write.table(merged, 'distances.tsv', sep="\t")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment