【问题标题】:how to calculate all pairwise distances in two dimensions如何计算二维的所有成对距离
【发布时间】:2011-07-26 05:05:17
【问题描述】:

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

此外,如何将其扩展到具有任意大偶数列的类似矩阵(每两列代表给定时间点的 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]

【问题讨论】:

    标签: r statistics 2d distance time-series


    【解决方案1】:

    恰如其分的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

    【讨论】:

      【解决方案2】:

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

      d^2&lt;-(((x1-x2)^2)+((y1-y2)^2))。花费会少很多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-30
        • 2017-12-20
        • 2017-05-16
        • 2016-04-06
        • 2013-09-02
        • 1970-01-01
        • 2016-11-16
        • 1970-01-01
        相关资源
        最近更新 更多