假设我有关于动物在 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<-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]

最佳答案

恰当命名的 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

关于r - 如何计算二维中的所有成对距离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5488688/

10-15 20:17