简体   繁体   中英

find 3 shortest distances in a matrix

I have a diagonal distance matrix of sites as per the below

     head(distancematrix)
          15001     15002    15003    15004     15005     15008     
15001    0.0000  252.9474 390.4716 858.7412 1082.2168 1262.6803 
15002  252.9474    0.0000 164.8057 608.5672  834.7632 1033.4702 
15003  390.4716  164.8057   0.0000 477.9417  755.8448  990.6740 
15004  858.7412  608.5672 477.9417   0.0000  370.3795  668.1066 
15005 1082.2168  834.7632 755.8448 370.3795    0.0000  303.5589 
15008 1262.6803 1033.4702 990.6740 668.1066  303.5589    0.0000  

I'd like to be able to get a data frame with each site in a row along with the distance of 3 shortest sites to it.

site  s1       s2        s3
15001 252.9474 390.4716 858.7412
15002 164.8057 608.5672  834.7632

You could try using apply. In this case, we are sorting each row, and taking the second to 4th values - the lowest is 0 which you have excluded. The output for row 2 doesnt match your example, as you have missed the 252.9474 point:

t(apply(dat, 1, function(x){sort(x)[2:4]}))

          [,1]     [,2]     [,3]
15001 252.9474 390.4716 858.7412
15002 164.8057 252.9474 608.5672
15003 164.8057 390.4716 477.9417
15004 370.3795 477.9417 608.5672
15005 303.5589 370.3795 755.8448
15008 303.5589 668.1066 990.6740

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