2
votes

I have two matrices with potentially both equal columns but unequal rows (but hopefully a solution will generalize to unequal numbers of both).

I would like the following behavior (demonstrated using data.frames):

x = data.frame(z = c(8, 9), w = c(10, 11))
y = data.frame(x = c(1, 2, 3), y = c(4, 5, 6))

> x
  z  w
1 8 10
2 9 11

> y
  x y
1 1 4
2 2 5
3 3 6

And I would like to do something like

magic_cbind(x, y)
   z   w  x  y
1  8  10  1  4
2  9  11  2  5
3 NA  NA  3  6

I found a perverse solution using rbind.fill from the plyr package:

> x = data.frame(t(x))
> y = data.frame(t(y))
> x
  X1 X2
z  8  9
w 10 11
> y
  X1 X2 X3
x  1  2  3
y  4  5  6
> rbind.fill(x, y)
  X1 X2 X3
1  8  9 NA
2 10 11 NA
3  1  2  3
4  4  5  6
> rbind.fill(x, y) %>% t %>% as.matrix %>% unname
     [,1] [,2] [,3] [,4]
[1,]    8   10    1    4
[2,]    9   11    2    5
[3,]   NA   NA    3    6

But I was wondering if there were a more elegant solution? I don't know the final size of the matrix in advance, which is a problem, and it grows inside a loop (which is terrible practice but it but won't grow large enough to actually be a concern). That is, given a matrix, I'm trying to bind additional columns obtained through a loop to it in the way described above.

I cobbled my solution up using the following questions:

Bind list with unequal columns

Combining (cbind) vectors of different length

R: column binding with unequal number of rows

3

3 Answers

2
votes

We can use cbind.fill from rowr

rowr::cbind.fill(x, y, fill = NA)
#    z  w x y
#1  8 10 1 4
#2  9 11 2 5
#3 NA NA 3 6
2
votes

Here's a way in base R:

as.data.frame(lapply(c(x,y),`length<-`,max(nrow(x),nrow(y))))

   z  w x y
1  8 10 1 4
2  9 11 2 5
3 NA NA 3 6
1
votes
 data.frame( sapply(c(x,y), '[', seq(max(lengths(c(x, y))))))


   z  w x y
1  8 10 1 4
2  9 11 2 5
3 NA NA 3 6

Or Use

library(magrittr)

library(purrr)

map_df(c(x, y), extract, seq(max(lengths(c(x, y)))))

or 
map_df(c(x,y), `[`, seq(max(lengths(c(x, y)))))


# A tibble: 3 x 4
      z     w     x     y
  <dbl> <dbl> <dbl> <dbl>
1  8.00  10.0  1.00  4.00
2  9.00  11.0  2.00  5.00
3 NA     NA    3.00  6.00