Re: [R] Add a Vector to a Matrix

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Sat, 26 Jul 2008 13:28:54 -0500

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



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 26 Jul 2008 - 18:31:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 26 Jul 2008 - 19:32:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive