Question: Extracting row and column names from matrix in R
0
gravatar for xxxxxxxx
9 days ago by
xxxxxxxx0
xxxxxxxx0 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 • 131 views
ADD COMMENTlink modified 9 days ago • written 9 days ago by xxxxxxxx0

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 22 hours ago by zx87547.1k
1
gravatar for zx8754
9 days ago by
zx87547.1k
London
zx87547.1k 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 9 days ago • written 9 days ago by zx87547.1k

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

ADD REPLYlink written 8 days ago by xxxxxxxx0

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

ADD REPLYlink written 8 days ago by zx87547.1k
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: 1618 users visited in the last hour