I want to add a new row to an existing matrix. Which R function should I use?

+4 votes

Best answer

You can use the **rbind()** function to add a new row to an existing R matrix. The number of columns in the new row should match the number of columns in the existing matrix, i.e., if the existing matrix has k columns, the new row should also have k columns.

Here is an example:

mm <- matrix(c(1:20), ncol = 4, nrow = 5)

mm <- rbind(mm, c(21:24))

The old value of the matrix 'mm':

> mm

[,1] [,2] [,3] [,4]

[1,] 1 6 11 16

[2,] 2 7 12 17

[3,] 3 8 13 18

[4,] 4 9 14 19

[5,] 5 10 15 20

The new value of the matrix 'mm':

> mm

[,1] [,2] [,3] [,4]

[1,] 1 6 11 16

[2,] 2 7 12 17

[3,] 3 8 13 18

[4,] 4 9 14 19

[5,] 5 10 15 20

[6,] 21 22 23 24