R语言 具有特定值的行名和列名

k7fdbhmy  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(175)

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

v1uwarro

v1uwarro1#

这里还有另一个选择:

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
ercv8c1e

ercv8c1e2#

你可以这样做:

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"
hfsqlsce

hfsqlsce3#

这里有一行答案

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"

相关问题