[R] Add a Vector to a Matrix

Marc Schwartz
Sat, 26 Jul 2008 18:28:54 -0000

on 07/26/2008 10:16 AM ascentnet wrote:
> I know there is a very simple answer to this question, but it eludes me.  I
> need to insert a vector into a matrix.  So if I have a 2 column matrix with
> 5 rows, I need to insert in an additional vector so there is now 6 rows
> without overwriting any of the data in the matrix already.
>
> thanks,
> Ben.

See ?rbind

mat <- matrix(1:10, ncol = 2)

 > mat
      [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10


Add the row to the end:

 > rbind(mat, c(6, 11))
      [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10
[6,]    6   11


Insert the row before the 5th row:

 > rbind(mat[1:4, ], c(6, 11), mat[5, ])
      [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    6   11
[6,]    5   10


HTH,

Marc Schwartz