R: Combine two matrices column by column
I have two matrices. I want to combine these, alternatingly picking the next column from a and from b.
> a <- matrix(c(rep(c(1:3),each=4)),4)
> a
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
[3,] 1 2 3
[4,] 1 2 3
> b <- matrix(c(rep(c(4:6),each=4)),4)
> b
[,1] [,2] [,3]
[1,] 4 5 6
[2,] 4 5 6
[3,] 4 5 6
[4,] 4 5 6
> matrix(rbind(a,b),4)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 4 2 5 3 6
[2,] 1 4 2 5 3 6
[3,] 1 4 2 5 3 6
[4,] 1 4 2 5 3 6
July 12th, 2007 at 10:33
Cool! How does that work?
July 12th, 2007 at 11:11
Hi Dan!
I’m surprised someone is actually reading this blog :)
rbindcombines a and b row by row. Thenmatrixgoes column by column through the oldrbind(a,b)matrix to pick the values that form the new matrix with just four rows.Before I found
rbind, I had this unwieldy solution:where
t(matrix(c(t(a),t(b)),3))does whatrbind(a,b)does.September 19th, 2007 at 09:10
Hello
I need to learn about :
the combine of two matrices.
thanke you very much
Jafari
September 28th, 2007 at 10:37
Hi Habib,
You’d need to be a bit more specific.
In general, just try out different things to see what they do. Here are some examples:
> a+b [,1] [,2] [,3] [1,] 5 7 9 [2,] 5 7 9 [3,] 5 7 9 [4,] 5 7 9 > c(a,b) [1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 > matrix(c(a,b),4) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 2 3 4 5 6 [2,] 1 2 3 4 5 6 [3,] 1 2 3 4 5 6 [4,] 1 2 3 4 5 6 > cbind(a,b) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 2 3 4 5 6 [2,] 1 2 3 4 5 6 [3,] 1 2 3 4 5 6 [4,] 1 2 3 4 5 6 > rbind(a,b) [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 2 3 [3,] 1 2 3 [4,] 1 2 3 [5,] 4 5 6 [6,] 4 5 6 [7,] 4 5 6 [8,] 4 5 6April 27th, 2010 at 16:56
Very useful. Thank you ;-)