简体   繁体   English

从 R 中的矩阵中提取行和列名称

[英]Extracting row and column names from matrix in R

My file is 1367*1367 long matrix like this-我的文件是这样的 1367*1367 长矩阵-

         MU101188    MU101310   MU101326    MU10251
MU101188    1          0             0          0
MU101310    0          1             0          0
MU101326    0          0             1          0
MU10251     0          0             0          1

I need to extract all pairs 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我需要提取值等于 1 的所有对。我使用以下 R 脚本,它给了我行号和列号,但我也想要名称

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

Building on the same steps, we can also use logic as below.基于相同的步骤,我们还可以使用如下逻辑。 (Not sure on inbuilt function to return the row,col as one-shot answer). (不确定内置函数是否返回行,col 作为一次性答案)。 Also tested this code with presence of multiple 1's in rows and it works.还测试了在行中存在多个 1 的代码并且它有效。

Code snippet below:下面的代码片段:

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

# just check the values
Pmatrix
sig_values

# incase there are multiple 1's in Pmatrix row 
# or one need to sort the order for the row-wise display
sig_values<-sig_values[order(sig_values[,1]),]
# remove the above line, incase there are no multiple 1's in input file or no sorting is desired

# code to get the desired rowname and colname 
i<-1
while (i <= nrow(sig_values)){

      # you can use whatever format and store in variabe or do your processing here
      # e.g. my format was (row,col), hence the paste format
      row_col<-paste("(",dimnames(Pmatrix)[[1]][sig_values[i,1]],",",dimnames(Pmatrix)[[2]][sig_values[i,2]],")")
  print(row_col)
    i<-i+1
}



 #Output
 [1] "( MU101188 , MU101188 )"
 [1] "( MU101310 , MU101310 )"
 [1] "( MU101326 , MU101326 )"
 [1] "( MU10251 , MU10251 )"       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM