[R] Add a Vector to a Matrix

Marc Schwartz marc_schwartz at comcast.net
Sat Jul 26 20:28:54 CEST 2008


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



More information about the R-help mailing list