rmatrixtriangular

Reading a symmetric matrix from file that omits upper triangular part


Using R, what is the best way to read a symmetric matrix from a file that omits the upper triangular part. For example,

1.000
.505  1.000
.569  .422  1.000
.602  .467  .926  1.000
.621  .482  .877  .874  1.000
.603  .450  .878  .894  .937  1.000

I have tried read.table, but haven't been successful.


Solution

  • Here's a read.table and loopless and *apply-less solution:

    txt <- "1.000
    .505  1.000
    .569  .422  1.000
    .602  .467  .926  1.000
    .621  .482  .877  .874  1.000
    .603  .450  .878  .894  .937  1.000"
     # Could use clipboard or read this from a file as well.
    mat <- data.matrix( read.table(text=txt, fill=TRUE, col.names=paste("V", 1:6))  )
    mat[upper.tri(mat)] <- t(mat)[upper.tri(mat)]
    > mat
            V1    V2    V3    V4    V5    V6 
    [1,] 1.000 0.505 0.569 0.602 0.621 0.603
    [2,] 0.505 1.000 0.422 0.467 0.482 0.450
    [3,] 0.569 0.422 1.000 0.926 0.877 0.878
    [4,] 0.602 0.467 0.926 1.000 0.874 0.894
    [5,] 0.621 0.482 0.877 0.874 1.000 0.937
    [6,] 0.603 0.450 0.878 0.894 0.937 1.000