我有以下矩阵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_mat
与mat1
的大小相同,在需要时添加零,并使colnames
和row.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
答案 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