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

+4 votes

You can use the **cbind() **function to add a new column to an R matrix. The number of rows in the new column should match the existing matrix. If the existing matrix has k rows, the new column should also have k rows.

Here is an example:

I have created a matrix 'mm' with 5 rows and 4 columns.

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

mm <- cbind(mm, c(21:25))

The old value of '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 'mm':

> mm

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

[1,] 1 6 11 16 21

[2,] 2 7 12 17 22

[3,] 3 8 13 18 23

[4,] 4 9 14 19 24

[5,] 5 10 15 20 25