计算R中2个位置之间的距离

时间:2020-09-23 07:17:09

标签: r

我有一个像这样的数据框[df]:

id  pos1                 pos2
1   -103.3671_43.0835    -103.3660_43.0812  
2   -103.3634_43.0855    -103.3656_43.0872  
3   -103.3684_43.0884    -103.3695_43.0890  
4   -103.3613_43.0835    -103.3600_43.0825

我想知道是否可以用米来计算pos1和pos2之间的距离吗?

非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

也许您可以尝试下面的代码

p1 <- as.data.frame(`class<-`(do.call(rbind,strsplit(df$pos1,"_")),"numeric"))
p2 <- as.data.frame(`class<-`(do.call(rbind,strsplit(df$pos2,"_")),"numeric"))

df$dist <- diag(geosphere::distm(p1,p2))

这样

> df
  id              pos1              pos2     dist
1  1 -103.3671_43.0835 -103.3660_43.0812 270.7631
2  2 -103.3634_43.0855 -103.3656_43.0872 260.3055
3  3 -103.3684_43.0884 -103.3695_43.0890 111.6475
4  4 -103.3613_43.0835 -103.3600_43.0825 153.4549

数据

> dput(df)
structure(list(id = 1:4, pos1 = c("-103.3671_43.0835", "-103.3634_43.0855", 
"-103.3684_43.0884", "-103.3613_43.0835"), pos2 = c("-103.3660_43.0812",
"-103.3656_43.0872", "-103.3695_43.0890", "-103.3600_43.0825"
)), class = "data.frame", row.names = c(NA, -4L))