简体   繁体   English

计算多个记录以匹配行的两点之间的距离-循环遍历两个矩阵的行

[英]Calculating distance between two points for multiple records for matching rows - loop over rows of two matrices

I have got two matrices with coordinates and I am trying to compute distances between points in matching rows, ie between row 1 in first matrix and row 1 in second matrix. 我有两个具有坐标的矩阵,我正在尝试计算匹配行中点之间的距离,即第一矩阵中的第1行与第二矩阵中的第1行之间的距离。

What I am getting is computed distance between row 1 and all the other rows. 我得到的是第1行与所有其他行之间的计算距离。 This is creating memory issues as I have 800,000 rows. 由于我有800,000行,因此造成了内存问题。 Does anyone know how to ask for that? 有谁知道该怎么要求?

I am using 我在用

dist1 <- distm(FareStageMatrix[1:25000,], LSOACentroidMatrix[1:25000,], fun=distHaversine)

I am trying to create something like this but doesn't seem to work 我正在尝试创建类似的东西,但似乎没有用

for(i in 1:nrow(FareStageMatrix)) {
    for(j in 1:nrow(LSOACentroidMatrix)) {
        my_matrix[i] <- my_matrix[distm(FareStageMatrix[i], LSOACentroidMatrix[i], fun=distHaversine)]
    }
}

changed to 变成

for (i in 1:nrow(FareStageMatrix)){
    for (i in 1:nrow(LSOACentroidMatrix)){
      r1<-FareStageMatrix[i,]
      r2<-LSOACentroidMatrix[i,]
      results[i]<-distm(r1, r2, fun=distHaversine)  
}
}

Is that something that should be working? 那应该起作用吗?

It seems I have managed to find a solution to that: 看来我设法找到了解决方案:

results<-matrix(NA,nrow(FareStageMatrix))

for (i in 1:nrow(FareStageMatrix)){
  for (i in 1:nrow(LSOACentroidMatrix)){
    r1<-FareStageMatrix[i,]
    r2<-LSOACentroidMatrix[i,]
    results[i]<-distm(r1, r2, fun=distHaversine)  ## Example function
  }
}

where FareStageMatrix and LSOACentroidMatrix are matrices with coordinates 其中FareStageMatrix和LSOACentroidMatrix是具有坐标的矩阵

It seems to have calculated one distance for a given pair of points 似乎已经计算出给定点对的一个距离

I've adapted geosphere 's distGeo function (geodesic distance) for this purpose. 我已经适应geospheredistGeo功能(测量距离)用于这一目的。

library(geosphere)
source("https://raw.githubusercontent.com/RomanAbashin/distGeo_v/master/distGeo_v.R")

Data 数据

set.seed(1702)

m1 <- matrix(runif(20000, -10, 10), ncol = 2) 
m2 <- matrix(runif(20000, -10, 10), ncol = 2)

Code

result <- distGeo_v(m1[, 1], m1[, 2], 
                    m2[, 1], m2[, 2])

Result 结果

> head(m1)
          [,1]      [,2]
[1,]  8.087152  9.227607
[2,]  9.528334  9.103403
[3,]  5.637921 -2.213228
[4,] -2.473758 -9.812986
[5,] -2.844036 -5.245779
[6,] -4.824615 -4.330890

> head(m2)
           [,1]       [,2]
[1,]  0.1673027  0.6483745
[2,] -2.5033184  0.1386050
[3,]  4.8589785  5.1996968
[4,]  8.3239454 -8.9810949
[5,]  0.8280422 -7.8272613
[6,] -6.2633738 -5.8725562

> head(result)
[1] 1292351.3 1661739.3  824260.0 1189476.4  496403.2  233480.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM