As the title says, I need to replace values in a symmetric matrix (A) with 0's according to col and row names given in another matrix (B). For instance,
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"
I tried
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
Specifically I need to replace A[A,D], A[B,E], A[C,E]
and A[B,C]
with 0 (above diagonal) and the same with A[D,A]
etc. (below diagonal).
Something like this?:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With