具有特定价值的rownames和colnames

时间:2013-04-02 09:46:47

标签: r matrix rowname

我有这个矩阵,我希望得到一个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

的对

提前致谢, 甲

3 个答案:

答案 0 :(得分:2)

这里有另一种选择:

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

答案 1 :(得分: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"

答案 2 :(得分: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"