简体   繁体   中英

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?

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.

I tried many ways to solved this without using the as.dist.

Any particular reason you can't use as.dist ? This is the closest I could get, using 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. (Also, if you need this as a matrix, you can of course wrap it in as.matrix ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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