Reputation: 69
How to rbind two matrix with different row numbers I have two matrix with different number of row, when I tried to combine them, there is error report:
A <- matrix (1:4, 2)
B <- matrix (6:11, 2)
rbind(A,B)
"Error in rbind(A, B): number of columns of matrices must match (see arg 2)"
I want
[,1] [,2] [,3]
[1,] 1 3
[2,] 2 4
[1,] 6 8 10
[2,] 7 9 11
Upvotes: 2
Views: 1777
Reputation: 29109
We can use plyr
package:
plyr::rbind.fill.matrix(A, B)
#> 1 2 3
#> [1,] 1 3 NA
#> [2,] 2 4 NA
#> [3,] 6 8 10
#> [4,] 7 9 11
Upvotes: 2
Reputation: 887501
We can convert to data.frame
and use bind_rows
. If the column names are not matching, it will fill NA
by default
library(dplyr)
out <- bind_rows(as.data.frame(A), as.data.frame(B))
as.matrix(out)
Upvotes: 2