I would like to merge two matrices based on row and column names. Here is an example:
mat1 <- matrix(c(0,0,1,0,1,0,1,1,0), nrow=3, byrow=TRUE)
colnames(mat1) <- c("A", "B", "C")
rownames(mat1) <- c("x", "y", "z")
mat1
A B C
x 0 0 1
y 0 1 0
z 1 1 0
mat2 <- matrix(0, nrow=4, ncol = 6)
colnames(mat2) <- c("A", "B", "C", "D", "E", "F")
rownames(mat2) <- c("w", "x", "y", "z")
mat2
A B C D E F
w 0 0 0 0 0 0
x 0 0 0 0 0 0
y 0 0 0 0 0 0
z 0 0 0 0 0 0
How can I efficiently write the values of mat1
into mat2
? I would like to obtain:
A B C D E F
w 0 0 0 0 0 0
x 0 0 1 0 0 0
y 0 1 0 0 0 0
z 1 1 0 0 0 0
I have tried for
loops but that seems tedious and inefficient. Ideas?