rownames and colnames with specific value

2019-02-25 21:42发布

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
X1  1 0   1
X2  0 1   0
X3  0 1   1
X4  1 0   0



str(x)
num [1:886, 1:886] 1 0 1 1 1 0 1 1 1 1

I want a matrix like this

# X1  X1 
# X1  X3   
# X2  X2   
# X3  X2   
# X3  X3   
# X4  X1   

which are the pairs that have value=1

Thanks in advance, A.

标签: r matrix rowname
3条回答
smile是对你的礼貌
2楼-- · 2019-02-25 21:50

Here's one line answer

x
##    X1 X2 X3
## X1  1  0  1
## X2  0  1  0
## X3  0  1  1
## X4  1  0  0


cbind(rownames(x)[row(x) * x], colnames(x)[col(x) * x])
##      [,1] [,2]
## [1,] "X1" "X1"
## [2,] "X4" "X1"
## [3,] "X2" "X2"
## [4,] "X3" "X2"
## [5,] "X1" "X3"
## [6,] "X3" "X3"
查看更多
冷血范
3楼-- · 2019-02-25 21:53

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"
查看更多
劳资没心,怎么记你
4楼-- · 2019-02-25 22:08

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
查看更多
登录 后发表回答