Extracting row and column names from matrix in R
1
0
Entering edit mode
5.0 years ago
xxxxxxxx ▴ 20
        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 • 8.4k views
ADD COMMENT
0
Entering edit mode

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.

ADD REPLY
1
Entering edit mode
5.0 years ago
zx8754 11k

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
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

Error says you have duplicated rownames, see related SO post:

ADD REPLY

Login before adding your answer.

Traffic: 2550 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6