rownames and colnames with specific value

前端 未结 3 1075
南方客
南方客 2021-01-22 15:26

I have this matrix and i want to get a 2 column matrix, where one column has the rowname and the other column, the colname of cells with value 1

x

   X1 X2 X3
         


        
3条回答
  •  时光说笑
    2021-01-22 15:43

    here another option :

    mm <- expand.grid(rownames(mat),colnames(mat))[as.vector(mat==1),]
    
     Var1 Var2
    1    X1   X1
    4    X4   X1
    6    X2   X2
    7    X3   X2
    9    X1   X3
    11   X3   X3
    

    And to get the OP display , we order by the first column:

     mm[order(mm$Var1),]
       Var1 Var2
    1    X1   X1
    9    X1   X3
    6    X2   X2
    7    X3   X2
    11   X3   X3
    4    X4   X1
    

    Here I mat is your imput , that I reproduce :

    mat <- data.frame(X1=c(1,0,0,1),X2=c(0,1,1,0),X3=c(1,0,1,0))
    rownames(mat)= paste0('X',1:4)
    
       X1 X2 X3
    X1  1  0  1
    X2  0  1  0
    X3  0  1  1
    X4  1  0  0
    

提交回复
热议问题