[R] Convert a List of Distances to a Distance Matrix

jim holtman jholtman at gmail.com
Thu Mar 13 02:48:42 CET 2008


Here is one way of doing it:

> x <- read.table(textConnection("A A 0
+ A B .5
+ A C .25
+ B C .5"), as.is=TRUE)
> closeAllConnections()
> # get the unique names
> x.names <- sort(unique(c(x[[1]], x[[2]])))
> # create a matrix of the right size and put names on it
> x.dist <- matrix(0, length(x.names), length(x.names))
> dimnames(x.dist) <- list(x.names, x.names)
> # create indices by converting names to numbers and create the normal and reversed
> # to fill in all the matrix
> x.ind <- rbind(cbind(match(x[[1]], x.names), match(x[[2]], x.names)),
+                cbind(match(x[[2]], x.names), match(x[[1]], x.names)))
> x.dist[x.ind] <- rep(x[[3]], 2)
> x.dist
     A   B    C
A 0.00 0.5 0.25
B 0.50 0.0 0.50
C 0.25 0.5 0.00
>


On Wed, Mar 12, 2008 at 7:45 PM, Charles Willis
<willis.charlie at gmail.com> wrote:
> Hello,
>
> Is there an easy function for switching list to matrix. My list is of
> genetic distances between species pairs:
>
> A A 0
> A B .5
> A C .25
> B C .5
>
> and I want a distance matrix such as:
>
>   A  B  C
> A 0  .5 .25
> B .5  0 .5
> C .25 .5 0
>
> for use in a mantel test.
>
> Thank you for the help!
>
> cheers,
> charlie
>
> --
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Charles G. Willis
> Department of Organismic and Evolutionary Biology
> 22 Divinity Ave Cambridge MA 02139
> HP (857) 488-2506
> WP (617) 496-3890
> cgwillis at oeb.harvard.edu
> http://www.people.fas.harvard.edu/%7Ecgwillis/
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list