Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Calculating distance in miles from one point to another

I have the following data frames:

library(dplyr)

d1 <- data_frame(
title = c("base1", "base2", "base3", "base4"),
lat = c(57.3, 58.8, 47.2, 57.8),
long = c(0.4, 3.4, 3.5, 1.2))

d2 <- data_frame(
tas = c("tas1", "tas2", "tas3", "tas4"),
Base= c ("base1", "base2", "base3", "base4"),
lat=c(54.6, 56.4, 54.2, 54.6),
long = c(1.2, 3.4, 3.5, 56.6))

What I would like to do is calculate the distance in miles between tas in d2 and title in d1. So in d2 tas1 has the coordinates 54.6 lat and 1.2 long, and has 'base1' in the 'Base' column. So I would like to calculate the distance between 54.6lat by 1.2long and 57.3lat and 0.4lon.

I've tried to do this using the GeoDistanceInMetresMatrix function as detailed below but the function doesn't quite give me the structure that I want.

The below article gives some information on GeoDistanceInMetresMatrix

http://eurekastatistics.com/calculating-a-distance-matrix-for-geographic-points-using-r/

This is what I would like the data to look like:

 df <- data_frame(
tas = c("tas1", "tas2", "tas3", "tas4"),
Base= c ("base1", "base2", "base3", "base4"),
lat=c(54.6, 56.4, 54.2, 54.6),
long = c(1.2, 3.4, 3.5, 56.6),
difference_miles = c(23, 35, 56, 23))

I've been looking at this all afternoon and can't quite get it right so any help would be appreciated!

like image 456
Mrmoleje Avatar asked Aug 13 '18 14:08

Mrmoleje


1 Answers

This is easily accomplished using the geosphere library:

d1 <- data.frame(
  title = c("base1", "base2", "base3", "base4"),
  lat = c(57.3, 58.8, 47.2, 57.8),
  long = c(0.4, 3.4, 3.5, 1.2))

d2 <- data.frame(
  tas = c("tas1", "tas2", "tas3", "tas4"),
  Base= c ("base1", "base2", "base3", "base4"),
  lat=c(54.6, 56.4, 54.2, 54.6),
  long = c(1.2, 3.4, 3.5, 56.6))

library(geosphere)
#1609.35 is the conversion from miles to meters
dist<-distGeo(d1[, c("long", "lat")], d2[, c("long", "lat")])/1609.35
df<-cbind(d2, difference_miles=dist)
like image 164
Dave2e Avatar answered Nov 02 '22 02:11

Dave2e