combine vectors by row in R by filling in empty spaces

Question:

I have two vectors:

a <- c(1,2,3,4)
b <- c(1,2)

I want to create a matrix combining the vectors per row that looks like this:

1 2 3 4
1 2 0 0

That is, joining two vectors by lines and filling the empty spaces with zeros.

Answer:

There is a smartbind function from the gtools package that does what you need

library(gtools)
smartbind(c(1,2,3,4), c(1,2), fill = 0)
Scroll to Top