如何通过合并R中的行来合并两个矩阵?
通过合并行意味着我们要连接矩阵的行,但是像在原始矩阵中那样创建单独的列。例如,如果我们有两个矩阵,请说M1和M2,如下所示-
M11 2 3
3 2 1
M2
2 3 5
1 2 3
然后通过合并行将这两个矩阵合并将导致-
1 2 3 2 3 53 2 1 1 2 3
例1
> M1<-matrix(rpois(40,5),nrow=20)输出结果> M1
[,1] [,2][1,] 5 2
[2,] 7 4
[3,] 3 6
[4,] 7 7
[5,] 5 3
[6,] 2 7
[7,] 4 7
[8,] 10 7
[9,] 7 2
[10,] 2 4
[11,] 7 5
[12,] 1 6
[13,] 2 3
[14,] 4 6
[15,] 7 6
[16,] 5 7
[17,] 3 2
[18,] 7 4
[19,] 9 6
[20,] 5 6
示例
> M2<-matrix(rpois(40,5),nrow=20)输出结果> M2
[,1] [,2][1,] 4 7
[2,] 2 9
[3,] 5 3
[4,] 2 10
[5,] 5 2
[6,] 5 5
[7,] 3 7
[8,] 6 5
[9,] 4 4
[10,] 5 0
[11,] 3 3
[12,] 5 2
[13,] 3 8
[14,] 2 6
[15,] 2 4
[16,] 10 5
[17,] 5 8
[18,] 1 4
[19,] 6 6
[20,] 4 6
按行合并M1和M2-
> merge(M1,M2,by="row.names",all=TRUE)输出结果
Row.names V1.xV2.xV1.y V2.y1 1 5 2 4 7
2 10 2 4 5 0
3 11 7 5 3 3
4 12 1 6 5 2
5 13 2 3 3 8
6 14 4 6 2 6
7 15 7 6 2 4
8 16 5 7 10 5
9 17 3 2 5 8
10 18 7 4 1 4
11 19 9 6 6 6
12 2 7 4 2 9
13 20 5 6 4 6
14 3 3 6 5 3
15 4 7 7 2 10
16 5 5 3 5 2
17 6 2 7 5 5
18 7 4 7 3 7
19 8 10 7 6 5
20 9 7 2 4 4
例2
> M3<-matrix(rpois(40,1),nrow=20)输出结果> M3
[,1] [,2][1,] 0 1
[2,] 0 1
[3,] 3 0
[4,] 2 0
[5,] 0 1
[6,] 2 1
[7,] 1 0
[8,] 2 0
[9,] 2 1
[10,] 0 1
[11,] 3 0
[12,] 2 0
[13,] 2 0
[14,] 1 2
[15,] 1 2
[16,] 0 1
[17,] 4 1
[18,] 1 1
[19,] 1 2
[20,] 1 1
示例
> M4<-matrix(rpois(40,1),nrow=20)输出结果> M4
[,1] [,2][1,] 1 0
[2,] 2 2
[3,] 1 0
[4,] 1 0
[5,] 0 2
[6,] 1 1
[7,] 2 0
[8,] 2 1
[9,] 0 0
[10,] 0 1
[11,] 3 0
[12,] 3 2
[13,] 3 5
[14,] 0 0
[15,] 2 1
[16,] 0 0
[17,] 1 1
[18,] 0 0
[19,] 1 1
[20,] 1 2
按行合并M3和M4-
> merge(M3,M4,by="row.names",all=TRUE)输出结果
Row.names V1.xV2.xV1.y V2.y1 1 0 1 1 0
2 10 0 1 0 1
3 11 3 0 3 0
4 12 2 0 3 2
5 13 2 0 3 5
6 14 1 2 0 0
7 15 1 2 2 1
8 16 0 1 0 0
9 17 4 1 1 1
10 18 1 1 0 0
11 19 1 2 1 1
12 2 0 1 2 2
13 20 1 1 1 2
14 3 3 0 1 0
15 4 2 0 1 0
16 5 0 1 0 2
17 6 2 1 1 1
18 7 1 0 2 0
19 8 2 0 2 1
20 9 2 1 0 0
以上是 如何通过合并R中的行来合并两个矩阵? 的全部内容, 来源链接: utcz.com/z/342605.html