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

dis*_*ved 13 statistics 2d r 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
Run Code Online (Sandbox Code Playgroud)

我想计算动物之间的所有成对距离.也就是说,获取动物a(第1行)到第2行,第3行......第15行中动物的距离,然后对所有行重复该步骤,避免冗余距离计算.执行此操作的函数的期望输出将是所有成对距离的平均值.我应该澄清我的意思是简单的线性距离,从公式d <-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]
Run Code Online (Sandbox Code Playgroud)

And*_*rie 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
Run Code Online (Sandbox Code Playgroud)

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