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