如何计算二维中的所有成对距离

时间:2011-03-30 15:45:26

标签: r statistics 2d distance time-series

说我有关于动物在2d平面上的位置的数据(通过直接在头顶上方的摄像机监视视频来确定)。例如,具有15行(每个动物1个)和2个列(x位置和y位置)的矩阵

animal.ids<-letters[1:15]  
xpos<-runif(15) # x coordinates 
ypos<-runif(15) # y coordinates 
raw.data.t1<-data.frame(xpos, ypos)
  rownames(raw.data.t1) = animal.ids

我想计算动物之间的所有成对距离。也就是说,获取动物a(第1行)到第2行,第3行......第15行中动物的距离,然后对所有行重复该步骤,避免冗余距离计算。执行此操作的函数的期望输出将是所有成对距离的平均值。我应该澄清,我的意思是简单的线性距离,从公式d&lt; -sqrt(((x1-x2)^ 2)+((y1-y2)^ 2))。任何帮助将不胜感激。

此外,如何将其扩展到具有任意大偶数列的类似矩阵(每两列代表给定时间点的x和y位置)。这里的目标是计算每两列的平均成对距离,并输出每个时间点及其对应的平均成对距离的表格。以下是具有3个时间点的数据结构示例:

xpos1<-runif(15) 
ypos1<-runif(15) 
xpos2<-runif(15) 
ypos2<-runif(15)
xpos3<-runif(15) 
ypos3<-runif(15)
pos.data<-cbind(xpos1, ypos1, xpos2, ypos2, xpos3, ypos3)
    rownames(pos.data) = letters[1:15]

2 个答案:

答案 0 :(得分:13)

恰当命名的dist()将执行此操作:

x <- matrix(rnorm(100), nrow=5)
dist(x)

         1        2        3        4
2 7.734978                           
3 7.823720 5.376545                  
4 8.665365 5.429437 5.971924         
5 7.105536 5.922752 5.134960 6.677726

有关详细信息,请参阅?dist

答案 1 :(得分:1)

为什么比较d&lt; -sqrt(((x1-x2)^ 2)+((y1-y2)^ 2))?

d ^ 2&lt; - (((x1-x2)^ 2)+((y1-y2)^ 2))。这将花费你更少。

相关问题