Convert and save distance matrix to a specific format Convert and save distance matrix to a specific format r r

Convert and save distance matrix to a specific format


This is quite doable using base R functions. First we want all pairwise combinations of the rows to fill the columns c1 and c2 in the resulting object. The final column distance is achieved by simply converting the "dist" object d into a numeric vector (it already is a vector but of a different class).

The first step is done using combn(rownames(x), 2) and the second step via as.numeric(d):

m <- data.frame(t(combn(rownames(x),2)), as.numeric(d))names(m) <- c("c1", "c2", "distance")

Which gives:

> m   c1  c2  distance1 aaa bbb 1.00000002 aaa ccc 0.66666673 aaa ddd 0.50000004 bbb ccc 0.33333335 bbb ddd 0.66666676 ccc ddd 0.3333333

To save as a CSV file, write.csv(m, file = "filename.csv").


you can do this by combining melt from reshape package, upper.tri etc.:

> library(reshape)> m <- as.matrix(d)> m          aaa       bbb       ccc       dddaaa 0.0000000 1.0000000 0.6666667 0.5000000bbb 1.0000000 0.0000000 0.3333333 0.6666667ccc 0.6666667 0.3333333 0.0000000 0.3333333ddd 0.5000000 0.6666667 0.3333333 0.0000000> m2 <- melt(m)[melt(upper.tri(m))$value,]> names(m2) <- c("c1", "c2", "distance")> m2    c1  c2  distance5  aaa bbb 1.00000009  aaa ccc 0.666666710 bbb ccc 0.333333313 aaa ddd 0.500000014 bbb ddd 0.666666715 ccc ddd 0.3333333