Search code examples
rr-corrplot

Replace one row and column in a matrix with a row and column from another matrix


I have two correlation matrixes. I want to replace row/column 5 of matrix 1 with row/column 5 of matrix 2.

matrix1 <-matrix(c(1:25),5, 5) 
colnames(matrix1)<-c("1","2","3","4","5") 
rownames(matrix1)<-c("A","B","C","D","E")

Looking like this (of cause with other numbers.)

   1  2  3  4  5
A  1  2  4  0  0
B  2  1  0  0  3
C  4  0  1  0  0
D  0  0  0  1  0
E  0  3  0  0  1

How can I replace row 5/column E from matrix1 with row 5/column E from matrix2?

I tried to work with it like a dataframe but that lead to nothing.


Solution

  • Are you asking to replace a single element located at row 5 and column 5, or are you asking 2 questions: how to replace row 5 and how to replace column 5?

    Assume 2 matrices:

    matrix1 <-matrix(c(1:25),5, 5) 
    colnames(matrix1)<-c("1","2","3","4","5") 
    rownames(matrix1)<-c("A","B","C","D","E")
    
    matrix2 <-matrix(-c(1:25),5, 5)
    

    Replace the single element at (5,5):

    matrix1[5,5] = matrix2[5,5]
    

    Replace row 5:

    matrix1[5,] = matrix2[5,]
    

    Replace column 5:

    matrix1[,5] = matrix2[,5]