Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values with 0 ins symetric matrix according to col, row names in a reference matrix

Tags:

r

matrix

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).

like image 206
JABalbuena Avatar asked Sep 01 '25 02:09

JABalbuena


1 Answers

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
like image 128
sgibb Avatar answered Sep 02 '25 15:09

sgibb