2

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
M--
  • 25,431
  • 8
  • 61
  • 93
IloveR
  • 39
  • 3
  • See https://stackoverflow.com/questions/16962576/how-can-i-rbind-vectors-matching-their-column-names – Axeman Jan 24 '20 at 21:45

2 Answers2

2

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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
M--
  • 25,431
  • 8
  • 61
  • 93