![](/img/trans.png)
[英]Calculate the distance between two coordinates columns group by individuals of different ID length in R
[英]How to calculate geographical distance between multiple individuals at same timestep in R
我有一個x和y GPS位置(十進制度)的矩陣(22467行和4列),用於多個人(ID,n = 13)的多個時間步(一小時)。 數據集示例(保存為csv文件):
ID Time x y
98427 01:00 43.97426 -59.56677
98427 02:00 43.97424 -60.56970
98428 01:00 43.97434 -60.52222
98428 02:00 43.97435 -59.24356
98429 01:00 43.97657 -59.36576
98429 02:00 43.97432 -59.98674
我想在每個時間步上計算所有組合之間每個人之間的距離。 因此,在時間= 01:00處,98427和98428、98427和98429、98428和98429之間的距離等。如何在R中做到這一點?
library(plyr)
data = iris
data = data[c(1:5, 81:85, 141:145), 3:5]
data$time = rep(1:5, 3)
dlply(data, .(time), function(x) {dist(x[ , 1:2])})
我只是玩過虹膜數據集,但是方法非常相似。
1.按時間拆分數據
2.使用x和y列並傳遞給dist()函數,該函數返回距離矩陣
3.將每個存儲為列表
然后,您可以從列表中拉出值,該列表中的每個條目都命名為時間。
更新:很抱歉天真地認為是歐氏距離。 這是Haversine距離的粗略實現。
library(geosphere)
havdist = function(x) {
n = dim(x)[1]
res = matrix(NA, nrow = n, ncol = n)
for (i in 1:n) {
k = 1
for (j in k:n) {
res[i, j] = res[j, i] = distHaversine(a[i, ], a[j, ])
}
n = n - 1
k = k + 1
}
return(res)
}
然后在上述dlply方法中提供havdist而不是dist。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.