[英]Calculate the distance between two coordinates columns group by individuals of different ID length in R
I have locations of individuals, and the dataframe is like: 我有个人的位置,数据框如下:
ID Lat Lon Distance
1 51.5184 -0.1382
1 51.5147 -0.1532
2 51.5184 -0.1342
2 51.5147 -0.1522
2 51.5537 -0.1556
... ... ...
and I would like to calculate the moving distance of each individual. 我想计算每个人的移动距离。 I am not very sure how to calculate the distances of points group by individuals in a dataframe.
我不太确定如何计算数据框中个人的点组距离。
I know there are some similar questions that posted before, such as this: How can I calculate the distance between latitude and longitude along rows of columns in R? 我知道之前发布过一些类似的问题,例如: 如何计算R中沿列行的纬度和经度之间的距离? I found our situation is a little different.
我发现我们的情况有点不同。 When I used this function:
当我使用这个功能时:
mutate(Distance = c(NA, distHaversine(cbind(Lon[-n()], Lat[-n()]), cbind(Lon[-1], Lat[-1]))))
in my work, I found the error subscript out of bounds
, and it means the ID are not of the same length. 在我的工作中,我发现错误
subscript out of bounds
,这意味着ID的长度不同。 Just like my data shows, I have 2 ID:1 and 3 ID:2, which leads to this problem. 就像我的数据显示的那样,我有2个ID:1和3 ID:2,这导致了这个问题。 I would really appreciate it if someone can tell me how to revise this function to fit my situation.
如果有人能告诉我如何修改这个功能以适合我的情况,我真的很感激。 Thanks.
谢谢。
mutate(df, Distance=distHaversine(cbind(Lon, Lat),cbind(lag(Lon),lag(Lat))))
对不起,我的坏 - 忘了distHaversine
需要一个矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.