【问题标题】:Assigning points to locations based on distance from coordinate in R根据与R中坐标的距离将点分配给位置
【发布时间】:2015-03-05 17:51:00
【问题描述】:

虽然有许多类似的主题(例如herehere),但我的最终目标与我在 SO 上看到的其他问题略有不同。作为参考,我使用的是 R v 3.1.0。

我有两个矩阵。每个都包含点的坐标。第一个 (A) 包含 2,107,377 个点,第二个 (B) 包含 26,577 个点。

我想在 B 中找到 A 中的每个点最接近的点。也就是说,我想计算 A 中的点 1 与 B 中的每个点之间的距离(26,577 距离),并存储最小值。我想为 A 中的每个点(2,107,377 最小值)执行此操作。目标是根据 B 中最接近的点将 A 中的点组合在一起。因此,B中的某些点将不会被分配;而其他人(很多)将被分配到A中的多个点。

我试过了:

test = which.min(sapply(1:nrow(coordinates), function(i) 
            spDistsN1(matrix(A, ncol = 2), matrix(B[i,], ncol = 2), 
                      longlat = TRUE)))

但遇到了内存分配问题(无法分配 >16 Mb 的向量)。

我现在正在运行一个 for 循环:

for (i in 1:nrow(A)) {
    minimum[i] = which.min(spDistsN1(matrix(A, ncol = 2), matrix(B[i,], ncol = 2), 
                                     longlat = TRUE))  
}

但是,我预计,这将导致相同的结果,只是更慢。

在尝试完全不同的方法(也许学习raster 包)之前,我想,我会看看是否有人有任何想法。

【问题讨论】:

    标签: r coordinates distance sp


    【解决方案1】:

    尝试将数据分解成更小的数据块,以免内存过载。 reproducible example 会有所帮助,但我认为这可以完成工作:

    library(sp)
    # X1 is a small example and X2 is a large example
    X1 <- cbind(pointX = 1:109, pointY = 1:109)
    Y1 <- cbind(x = 11:20, y = 11:20)
    
    X2 <- cbind(pointX  = 2e4 + sample(2e6), pointY  = 2e4 + sample(2e6))
    Y2 <- cbind(x = sample(2e4), y = sample(2e4))
    
    nearWrapper = function(X, Y, nBatches = 10){
        maxNumber = dim(X)[1]
        batchNumbers <- split(0:maxNumber, ceiling(seq_along(0:maxNumber)/nBatches))
        out <- numeric(maxNumber)
        for(batch in 1:(nBatches+1)){
            out[batchNumbers[[batch]]] <- apply(spDists(X[batchNumbers[[batch]],], Y), 1, which.min)
            }   
        return(out)
    }
    smallOut <- nearWrapper(X1, Y1)
    largeOut <- nearWrapper(X2, Y2)
    

    如果您的数据耗时过长,您还可以检查并行计算(在您的情况下使用foreach 循环代替for 循环)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-20
      • 2016-10-28
      • 2016-11-15
      • 1970-01-01
      • 2017-06-21
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多