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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With