正如标题所说,我需要根据另一个矩阵(B)中给出的col和row名称将对称矩阵(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
具体来说,我需要将A[A,D], A[B,E], A[C,E]
和A[B,C]
替换为0(对角线以上),将A[D,A]
等替换为({对角线以下)。
答案 0 :(得分:4)
这样的东西?:
A[rbind(B, B[,2:1])] <- 0 # B[,2:1] swaps rows/columns reference
A
# A B C D E
#A 0 1 2 0 4
#B 1 0 0 2 0
#C 2 0 0 1 0
#D 0 2 1 0 3
#E 4 0 0 3 0