Search code examples
rcsvmatrixrowcol

Extracting row and column names with its value from matrix


my matrix is like this-

          MU101188  MU101310    MU101326    MU10251
MU101188    1        0.506       -0.006     -0.006
MU101310   -0.006       1        -0.006     -0.006
MU101326  -0.006    -0.006            1     -0.006
MU10251   -0.006    -0.006        0.806         1

I need to extract all pairs with their value for which the value is greater than or equal to 0.5. I m using the following R script which gives me the row and column name, but I also want a 3rd column consist of its value

Pmatrix = read.csv ("file.csv", header= TRUE, row.names = 1)
sig_values <- which(Pmatrix>=0.5, arr.in=TRUE)
cbind.data.frame(colIDs = colnames(Pmatrix)[ sig_values[, 1] ],rowIDs = rownames(Pmatrix)[ sig_values[, 2] ] )

Solution

  • You could use sig_values to subset Pmatrix

    cbind.data.frame(colIDs = colnames(Pmatrix)[sig_values[, 1]],
                     rowIDs = rownames(Pmatrix)[sig_values[, 2]], 
                     values = Pmatrix[sig_values])
    
    
    #    colIDs   rowIDs values
    #1 MU101188 MU101188  1.000
    #2 MU101188 MU101310  0.506
    #3 MU101310 MU101310  1.000
    #4 MU101326 MU101326  1.000
    #5  MU10251 MU101326  0.806
    #6  MU10251  MU10251  1.000