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)?
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
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