在R中添加一列两个坐标的距离

时间:2014-01-10 04:03:39

标签: r gis

我有一个类似的数据框:

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

如何让dist成为距离点(lat1,lng1)到点(lat2,lng2)的距离(?)

1 个答案:

答案 0 :(得分:7)

您可以将applygdist包中的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