【发布时间】:2015-10-29 10:25:35
【问题描述】:
我想使用地理位置创建公司之间的距离矩阵。
我有一个平方距离矩阵,其中包含 98 个意大利省份之间的距离。我还有一个包含两列的数据框。一栏有 8376 家公司的 ID 号。另一列表示这些公司各自位于 98 个省中的哪个省。
我想创建一个 8376 x 8376 距离矩阵,其中包含所有公司之间的距离。我编写的代码(如下)效率极低。有没有办法更快地做到这一点?我问是因为我需要对多个数据集进行此操作。
这就是数据框的样子
cid province
1 61 TO
2 102 TO
3 123 AT
4 127 TO
5 158 TO
6 225 NO
7 232 TO
8 388 TO
这就是平方距离矩阵的样子
CH AQ PE TE
1 0 64.39 41.74 81.18
2 64.39 0 40.38 61.05
3 41.74 40.38 0 40.79
4 81.18 61.05 40.79 0
outcome = matrix(NA,8376,8376) # empty matrix
for(i in 1:8376){
for(j in (i+1):8376){
x=which(dist.codes[,1]==companyID_Province[i,2]) # Find the row index in the distance matrix
y=which(dist.codes[1,]==companyID_Province[j,2]) # Find the column index in the distance matrix
outcome[i,j] = dist.codes[x,y] # Specify the distance to the corresponding element in outcome matrix
}
}
【问题讨论】:
-
请提供一个可重现的例子。显示
dist.codes和company_Province的一小部分。 -
在您的代码中,
outcome[i,j] = dist.codes[x,y]表明dist.codes是各省的距离矩阵。但随后y=which(dist.codes[1,]==companyID_Province[j,2])将距离与公司 ID 进行比较。 -
dist.codes 是各省的距离矩阵。 x 是行索引,y 是列索引。两者都使用 companyID_Province 数据框。我现在已经更正了,和以前一样有一个错误。在我运行的代码中它是正确的,但仍然需要 24 小时以上,因为有数百万个单元格要填充
-
嗨 Nicola,我目前正在运行代码,所以我现在不能发布子集。我今天晚些时候会做(如果运行终止)。数据框“companyID_Province”为 8376*2。平方距离矩阵“dist.codes”为 98*98
-
您的代码只使用了一列
companyID_Province,即第二列。第一列有什么用?第二列是否包含 ID 或省份?