Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column of distances of two coordinates in R

Tags:

r

gis

I have a data frame like that:

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 dist be the distance in meters from point (lat1, lng1) to point (lat2, lng2)?

like image 464
Allan Veloso Avatar asked Mar 22 '23 01:03

Allan Veloso


1 Answers

You could use apply with the gdist function from the Imap package:

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
like image 148
josliber Avatar answered Apr 01 '23 21:04

josliber