How to Add New Column to Matrix in R (With Examples)


You can use the following methods to add a new column to a matrix in R:

Method 1: Add New Column to End of Matrix

my_matrix <- cbind(my_matrix, c(2, 7, 7, 8))

Method 2: Add New Column to Beginning of Matrix

my_matrix <- cbind(c(2, 7, 7, 8), my_matrix)

Note that both methods use the cbind() function in R to column-bind a new column to the matrix.

The following examples show how to use each method in practice.

Example 1: Add New Column to End of Matrix

The following code shows how to use the cbind() function to add a new column to the last position of a matrix that contains the values 2, 7, 7, and 8:

#create matrix
my_matrix <- matrix(c(14, 0, 12, 5, 7, 4, 1, 3, 9, 5, 5, 8), nrow=4)

#view matrix
my_matrix

     [,1] [,2] [,3]
[1,]   14    7    9
[2,]    0    4    5
[3,]   12    1    5
[4,]    5    3    8

#add new column to end of matrix
my_matrix <- cbind(my_matrix, c(2, 7, 7, 8))

#view updated matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]   14    7    9    2
[2,]    0    4    5    7
[3,]   12    1    5    7
[4,]    5    3    8    8

Notice that one new column has been added to the end of the matrix.

Example 2: Add New Column to Beginning of Matrix

The following code shows how to use the cbind() function to add a new column to the first position of a matrix that contains the values 2, 7, 7, and 8:

#create matrix
my_matrix <- matrix(c(14, 0, 12, 5, 7, 4, 1, 3, 9, 5, 5, 8), nrow=4)

#view matrix
my_matrix

     [,1] [,2] [,3]
[1,]   14    7    9
[2,]    0    4    5
[3,]   12    1    5
[4,]    5    3    8

#add new column to beginning of matrix
my_matrix <- cbind(c(2, 7, 7, 8), my_matrix)

#view updated matrix
my_matrix

     [,1] [,2] [,3] [,4]
[1,]    2   14    7    9
[2,]    7    0    4    5
[3,]    7   12    1    5
[4,]    8    5    3    8

Notice that one new column has been added to the beginning of the matrix.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Sort a Matrix in R
How to Remove NA from Matrix in R
How to Convert Data Frame to Matrix in R
How to Convert a Table to a Matrix in R

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *