Convert and save distance matrix to a specific format

前端 未结 2 1018
执笔经年
执笔经年 2020-12-13 07:09

I got a distance matrix with the following steps:

x <- read.table(textConnection(\'
     t0 t1 t2
 aaa  0  1  0
 bbb  1  0  1
 ccc  1  1  1
 ffffd  1  1  0
         


        
相关标签:
2条回答
  • 2020-12-13 07:50

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

    > library(reshape)
    > m <- as.matrix(d)
    > m
              aaa       bbb       ccc       ffffd
    aaa 0.0000000 1.0000000 0.6666667 0.5000000
    bbb 1.0000000 0.0000000 0.3333333 0.6666667
    ccc 0.6666667 0.3333333 0.0000000 0.3333333
    ffffd 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  distance
    5  aaa bbb 1.0000000
    9  aaa ccc 0.6666667
    10 bbb ccc 0.3333333
    13 aaa ffffd 0.5000000
    14 bbb ffffd 0.6666667
    15 ccc ffffd 0.3333333
    
    0 讨论(0)
  • 2020-12-13 07:59

    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  distance
    1 aaa bbb 1.0000000
    2 aaa ccc 0.6666667
    3 aaa ffffd 0.5000000
    4 bbb ccc 0.3333333
    5 bbb ffffd 0.6666667
    6 ccc ffffd 0.3333333
    

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

    0 讨论(0)
提交回复
热议问题