我将距离矩阵转换为两列data.frame
,我想过滤掉“对角线”和“> 0”值,并保持相同的对象。
我有一个距离矩阵,例如
mat<-c(0,0.5,0,0.5,0,0.3,0,0.3,0)
dim(mat)<-c(3,3)
rownames(mat)<-c("A","B","C")
colnames(mat)<-c("A","B","C")
我尝试过
df = as.data.table(mat)
df1 <- stack(df)
setDT(df1)
df1[, pp := colnames(df)]
setkey(df1, values)
哪个给
values ind pp
1: 0.0 A A
2: 0.0 A C
3: 0.0 B B
4: 0.0 C A
5: 0.0 C C
6: 0.3 B C
7: 0.3 C B
8: 0.5 A B
9: 0.5 B A
我需要什么:
values ind pp
1: 0.0 A C
答案 0 :(得分:1)
这是一种实现方法:
mat <- c(1,0.5,0,0.5,1,0.3,0,0.3,1)
dim(mat) <- c(3,3)
rownames(mat) <- c("A","B","C")
colnames(mat) <- c("A","B","C")
cond <- mat == 0 & upper.tri(mat, FALSE)
pos <- which(cond, arr.ind = TRUE)
data.frame(values = mat[pos], ind = rownames(mat)[pos[,1]], pp = rownames(mat)[pos[,2]])
cond是您条件的布尔矩阵,值等于0,不是用于删除对称矩阵的重复索引的诊断和上三角矩阵。