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

时间:2017-01-10 15:18:07

标签: r matrix rbind

我有以下矩阵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.names保持与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

我尝试过丢失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

1 个答案:

答案 0 :(得分:4)

这会将small_mat插入零&#39; d矩阵

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