15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Add New Column to Matrix in R (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 

Method 2: Add New Column to Beginning of Matrix

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 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 #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 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 #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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories