This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Extracting row and column names from matrix in R
        MU101188        MU101310           MU101326             MU10251
MU101188    1                  0                  0                   0
MU101310    0                  1                  0                   1
MU101326    0                  1                  1                   0
MU10251     1                  0                  0                   1

I need to extract all pairs of MU ids for which the value is equal to 1. I m using the following R script which gives me the row and column number, but I also want the names

Pmatrix = read.csv ("file.csv", header = TRUE, row.names = 1) 
    sig_values <- which(Pmatrix==1, arr.in= TRUE)
r

Hello xxxxxxxx!

It appears that your post has been cross-posted to another site: https://stackoverflow.com/q/55702350/680068

This is typically not recommended as it runs the risk of annoying people in both communities.

1 answer

Using your approach, subset colnames and rownames by index:

cbind.data.frame(
  colIDs = colnames(Pmatrix)[ sig_values[, 1] ],
  rowIDs = rownames(Pmatrix)[ sig_values[, 2] ])

#     colIDs   rowIDs
# 1 MU101188 MU101188
# 2 MU101310 MU101310
# 3 MU101326 MU101326
# 4  MU10251  MU10251

Or using tidyverse, reshape from wide-to-long then filter:

library(tidyverse)

Pmatrix %>% 
  rownames_to_column("id") %>% 
  gather(key = "key", value = "value", -id) %>% 
  filter(value == 1)

#         id      key value
# 1 MU101188 MU101188     1
# 2 MU101310 MU101310     1
# 3 MU101326 MU101326     1
# 4  MU10251  MU10251     1

Error in read.table(file = file, header = header, sep = sep, quote = quote, : duplicate 'row.names' are not allowed

Log in to answer this question.