简体   繁体   English

将距离列表转换为距离矩阵,而无需在R中使用as.dist

[英]Convert a list of distances to a distance matrix without using as.dist in R

I have a list of distances from point A to point B. How to convert the list to distance matrix without using as.dist? 我有一个从A点到B点的距离列表。如何在不使用as.dist的情况下将列表转换为距离矩阵?

Here's the data: 数据如下:

 AB Distance 3 10 0.2 6 9 0.2 3 5 0.4 9 10 0.4 4 8 0.5 4 5 0.6 6 7 0.7 1 2 1.4 2 10 2.6 

The output should be like this: 输出应如下所示:

  1 2 3 4 5 6 7 8 9 10 1 0 1.4 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 3 0 0 0.4 0 0 0 0 0.2 4 0 0.6 0 0 0.5 0 0 5 0 0 0 0 0 0 6 0 0.7 0 0.2 0 7 0 0 0 0 8 0 0 0 9 0 0.4 10 0 

'0' indicates that there are no link between points. “ 0”表示点之间没有链接。

I tried many ways to solved this without using the as.dist. 我尝试了多种方法来解决此问题,而无需使用as.dist。

Any particular reason you can't use as.dist ? 您无法使用as.dist任何特殊原因吗? This is the closest I could get, using tidyr : 这是我使用tidyr可以获得的最接近的tidyr

spread(data,B,distance,fill=0,drop=FALSE)

This works best if all A's and B's have at least one of each value somewhere in the dataset, and it gives you both halves of the matrix. 如果所有A和B在数据集中的某处至少具有每个值中的一个,则此方法效果最佳,并且可以为您提供矩阵的两半。 (Also, if you need this as a matrix, you can of course wrap it in as.matrix ). (此外,如果您需要将其作为矩阵,则当然可以将其包装为as.matrix )。

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

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