rownames and colnames with specific value

前端 未结 3 1078
南方客
南方客 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:35

    You can do something like this :

    mat <- which(x==1, arr.ind=TRUE)
    mat[,"col"] <- names(x)[mat[,"col"]]
    mat[,"row"] <- rownames(mat)
    

    Which will give :

       row  col 
    X1 "X1" "X1"
    X4 "X4" "X1"
    X2 "X2" "X2"
    X3 "X3" "X2"
    X1 "X1" "X3"
    X3 "X3" "X3"
    

提交回复
热议问题