SushantG
SushantG

Reputation: 83

How to calculate distance between multiple lon lat vectors using R

My data set is as below-

a
Location   loc.Lon   loc.Lat  Pincode      pin.lon     pin.lat
SPM        79.94533 12.97025 "602105"   79.95285     12.96752
SPM        79.94533 12.97025 "602106"   79.88568     12.91943

I want to calculate the distance between (loc.Lon, loc.Lat) and (pin.lon, pin.lat) for both the pincodes using the package ggmap.

when I run the below code, I get the desired result -

mapdist(c(a$loc.Lon[2], a$loc.Lat[2]), c(a$pin.lon[2],a$pin.lat[2]), mode = "driving") 

but when I run the below query for the entire data set a, I get an error -

a$dist = mapdist(c(a$loc.Lon, a$loc.Lat), c(a$pin.lon,a$pin.lat), mode = "driving")

error I get is -

Error: is.character(from) is not TRUE

Please help me getting this sorted.

Upvotes: 2

Views: 2416

Answers (2)

msoderstrom
msoderstrom

Reputation: 537

Cast the coordinates as strings with as.character() and paste0() them when calling mapdist directly onto your data.

a$dist_km <- mapdist(from = paste0(as.character(a$loc.Lat),",",as.character(a$loc.Lon)),
                     to = paste0(as.character(a$pin.Lat),", ",as.character(a$pin.Lon)))[,c('km')]

Upvotes: 1

ztl
ztl

Reputation: 2592

mapdist accepts vectors for the from and to arguments, so you can convert them and apply this function to each line of you data set.

Supposing you want the km distance:

get_km_from_mapdist <- function(i) {
  mapdist(as.numeric(a[i, c('loc.Lon','loc.Lat')]), 
          as.numeric(a[i, c('pin.lon','pin.lat')]), 
          mode='driving')$km
}

a$dists = sapply(1:nrow(a), get_km_from_mapdist)

Upvotes: 4

Related Questions