【问题标题】:Calculate average distance between point and closest neighbors in R计算R中点和最近邻居之间的平均距离
【发布时间】:2015-01-07 03:38:17
【问题描述】:

我正在尝试计算给定点与其最近邻居的 x 个之间的平均距离,以了解数据集的点与其邻居之间的距离。虽然使用earth.dist() 提供了所有点(和全局平均值)之间的完整距离矩阵,但我想找到一个点与其 5 个最近邻居之间的距离。例如:

frame <- data.frame(long = rnorm(100), lat = rnorm(100))
earth.dist(frame)
mean(earth.dist(frame))  # provides the global mean

非常感谢任何帮助您找到最近的邻居。

【问题讨论】:

    标签: r distance geo


    【解决方案1】:

    要获得每个点的 5 个最近邻,您可以这样做

    library(fossil)
    set.seed(15)
    frame <- data.frame(long = rnorm(100), lat = rnorm(100))
    ed <- earth.dist(frame)
    closen <- apply(as.matrix(ed), 1, function(x) order(x)[1:6][-1])
    

    所以第一个点的最近邻居的索引是

    closen[,1]
    # [1] 41 26 13 75  7
    

    【讨论】:

      【解决方案2】:

      我只会排序并取 first 的平均值(除了它的自距离):

      distM <- as.matrix( fossil::earth.dist(frame))
      apply( distM, 1, function(x) mean( x[order(x)][2:6] ) )
      #----------
              1         2         3         4         5         6         7 
       93.57153  56.06655 129.84690  95.13023  55.96412  70.57303  55.60863 
              8         9        10        11        12        13        14 
      111.79244  17.56394  34.10893  21.80423  20.30025  29.57373  31.13890 
      snipped
      

      【讨论】:

        【解决方案3】:

        我也想出了如何使用lapply() 来做到这一点。

        distM <- as.matrix( fossil::earth.dist(frame))
        unlist(lapply(1:nrow(distM), function(x) mean(distM[x, order(distM[x, ])[2:6]])))
        

        【讨论】:

          猜你喜欢
          • 2018-12-20
          • 2011-11-12
          • 2020-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-16
          • 2018-05-21
          • 2017-06-25
          相关资源
          最近更新 更多