如何基于行和列名称合并矩阵

时间:2019-04-15 14:39:33

标签: r matrix

我想基于行和列的名称合并两个矩阵。这是一个示例:

system.???.watch(child, getRef());
expectMsgClass(Terminated.class);
// Check that Terminated.actor is child

如何有效地将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 的值写入mat1?我想获得:

mat2

我尝试了 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 循环,但这似乎很乏味且效率低下。想法?

1 个答案:

答案 0 :(得分:3)

如果“ mat2”是“ mat1”的超集,则使用行/列索引对“ mat2”进行子集并分配“ mat1”

mat2[row.names(mat1), colnames(mat1)] <- mat1
mat2
#   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