4

我有这个矩阵,我想得到一个 2 列矩阵,其中一列具有行名,另一列是值为 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

我想要这样的矩阵

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

哪些是 value=1 的对

在此先感谢,A。

4

3 回答 3

3

这里有另一个选择:

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 display ,我们按第一列排序:

 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
于 2013-04-02T10:38:14.550 回答
1

你可以这样做:

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"
于 2013-04-02T10:24:03.570 回答
0

这是一行答案

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"
于 2013-04-02T11:27:28.960 回答