根据保持 colname 顺序的其他矩阵的长度向数据矩阵添加零

Add zeros to data matrix based on length of other matrix keeping colname order

我有下面的矩阵mat1:

mat1 <- matrix (1:16, 4)
colnames(mat1) <- c("A1","B2","C3","D4"); row.names(mat1) <- c("A1","B2","C3","D4")

 mat1
   A1 B2 C3 D4
A1  1  5  9 13
B2  2  6 10 14
C3  3  7 11 15
D4  4  8 12 16

我还有一个更小的矩阵small_mat:

small_mat <- matrix (1:4, 2)
colnames(small_mat) <- c("A1","C3"); row.names(small_mat) <- c("A1","C3")

  A1 C3
A1  1  3
C3  2  4

我想使 small_matmat1 大小相同,在需要的地方添加零并保持 colnamesrow.namesmat1 的顺序相同].

想要的结果:

       A1 B2 C3 D4
    A1  1  0  3  0
    B2  0  0  0  0
    C3  2  0  4  0
    D4  0  0  0  0

我试过用缺失的 small_mat colnames 制作一个零矩阵,然后使用 rbind.fill.matrix 但没有完全做到:

not_in_small_mat <- colnames(mat1)[!(colnames(mat1) %in% colnames(small_mat))] # see what colnames are missing from small_mat 
zeros <- matrix(data=0,nrow=length(not_in_small_mat),ncol=length(colnames(mat1))) # create matrix of those needing adding 
colnames(zeros) <- colnames(mat1)

result <- rbind.fill.matrix(small_mat,zeros)

    A1 C3 B2 D4
[1,]  1  3 NA NA
[2,]  2  4 NA NA
[3,]  0  0  0  0
[4,]  0  0  0  0

这会将 small_mat 插入零矩阵

mat1 <- matrix(rep(0, 16), 4)
colnames(mat1) <- c("A1", "B2", "C3", "D4")
row.names(mat1) <- c("A1", "B2", "C3", "D4")

small_mat <- matrix(1:4, 2)
colnames(small_mat) <- c("A1", "C3")
row.names(small_mat) <- c("A1", "C3")

mat1[rownames(small_mat), colnames(small_mat)] <- small_mat

mat1
   A1 B2 C3 D4
A1  1  0  3  0
B2  0  0  0  0
C3  2  0  4  0
D4  0  0  0  0