正如标题所说,我需要根据另一个矩阵 (B) 中给出的列名和行名将对称矩阵 (A) 中的值替换为 0。例如,
A <-matrix(c(0,1,2,3,4,1,0,1,2,3,2,1,0,1,2,3,2,1,0,3,4,3,2,3,0), 5)
colnames(A) <- rownames(A) <-c(LETTERS[1:5])
A
A B C D E
A 0 1 2 3 4
B 1 0 1 2 3
C 2 1 0 1 2
D 3 2 1 0 3
E 4 3 2 3 0
B <- matrix(c("A","B","C","B","D","E","E","C"),4)
B #reference matrix
[,1] [,2]
[1,] "A" "D"
[2,] "B" "E"
[3,] "C" "E"
[4,] "B" "C"
我试过了
A[B[,1],B[,2]]<-0 #for the above-diagonal half but it didn't work as I expected:
A
A B C D E
A 0 1 0 0 0
B 1 0 0 0 0
C 2 1 0 0 0
D 3 2 1 0 3
E 4 3 2 3 0
具体来说,我需要用 0 (对角线上方)替换A[A,D], A[B,E], A[C,E]
和等。(对角线下方)。A[B,C]
A[D,A]