rownames和colnames与特定值(rownames and colnames with s

2019-08-18 23:57发布

我有这个矩阵,我想获得一个2列的矩阵,其中一列有rowname和其他列,细胞与值1 colname的

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

我想这样的矩阵

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

其是具有值的双= 1

在预先感谢A.

Answer 1:

这里的另一种选择:

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

并获得了OP显示,我们为了在第一列:

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

在这里,我垫的开关输入,那我重现:

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


Answer 2:

你可以这样做:

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

这将给:

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


Answer 3:

下面是一行答案

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"


文章来源: rownames and colnames with specific value
标签: r matrix rowname