combine vectors per line in R by filling voids

Asked

Viewed 381 times

4

I have two vectors:

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

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

1 2 3 4
1 2 0 0

That is, unite two vectors by rows and fill the empty spaces with zeros.

2 answers

2


There is the function smartbind package gtools who does what you need

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

1

You can increase the vector b to be the same size as the vector a including zeroes:

rbind(a, b = c(b, rep(0, length(a) - length(b))))
  [,1] [,2] [,3] [,4]
a    1    2    3    4
b    1    2    0    0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.