Add a column of distances of two coordinates in R

I have a data frame like this:

id    value    lat1         lng 1       lat2         lng2           dist
124   50.4     -13.2423    -46.2342     -13.2423    -46.2342        ???
537   34.2     -13.2434    -46.2331     -13.2423    -46.2342        ???
891   42.0     -13.2445    -46.2389     -13.2423    -46.2342        ???

How can I make the distdistance in meters from the point (lat1, lng1) to the point (lat2, lng2)?

+4
source share
1 answer

You can use applywith the function gdistfrom the package Imap:

library(Imap)
df = data.frame(id=c(124, 537, 891),
                value=c(50.4, 34.2, 42.0),
                lat1=c(-13.2423, -13.2434, -13.2445),
                lng1=c(-46.2342, -46.2331, -46.2389),
                lat2=c(-13.2423, -13.2423, -13.2423),
                lng2=c(-46.2342, -46.2342, -46.2342))
df$dist = apply(df, 1, function(x) gdist(x["lng1"], x["lat1"],
                                         x["lng2"], x["lat2"], units="m"))
df
#    id value     lat1     lng1     lat2     lng2     dist
# 1 124  50.4 -13.2423 -46.2342 -13.2423 -46.2342   0.0000
# 2 537  34.2 -13.2434 -46.2331 -13.2423 -46.2342 170.3595
# 3 891  42.0 -13.2445 -46.2389 -13.2423 -46.2342 564.5390
+7
source

All Articles