Question: Extracting row and column names from matrix in R
0
gravatar for xxxxxxxx
10 months ago by
xxxxxxxx20
xxxxxxxx20 wrote:
        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 • 1.5k views
ADD COMMENTlink modified 10 months ago • written 10 months ago by xxxxxxxx20

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 REPLYlink written 10 months ago by zx87549.0k
1
gravatar for zx8754
10 months ago by
zx87549.0k
London
zx87549.0k wrote:

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 COMMENTlink modified 10 months ago • written 10 months ago by zx87549.0k

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

ADD REPLYlink written 10 months ago by xxxxxxxx20

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

ADD REPLYlink written 10 months ago by zx87549.0k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1615 users visited in the last hour