Table of contents
1.
Introduction
2.
Creating a Matrix
2.1.
Using matrix() function
2.1.1.
Syntax
2.1.2.
Example: Let’s create a 3x3 matrix with data - 1,2,3,4,5,6,7,8,9 
2.2.
Using Vectors
2.2.1.
Syntax 
2.2.2.
Example 
2.3.
Create a row-wise matrix
2.3.1.
Syntax 
2.3.2.
Example 
3.
Naming the rows and columns
3.1.
Creating new matrix with column and row names 
3.1.1.
Syntax
3.1.2.
Example 
3.2.
Assign names of rows and columns to an existing matrix 
3.2.1.
Syntax 
3.2.2.
Example 
4.
Accessing Elements of a Matrix
4.1.
Using Number Index
4.1.1.
Syntax
4.1.2.
Example 
4.2.
Using logical vectors as an index
4.2.1.
Syntax
4.2.2.
Example 
4.3.
Using a Character vector as an index 
4.3.1.
Syntax
4.3.2.
Example
5.
Modify a Matrix
5.1.
Modify the value stored
5.1.1.
Example
5.2.
Add new rows or columns 
5.2.1.
Syntax
5.2.2.
Example 
5.3.
Modifying dimensions 
5.3.1.
Syntax
5.3.2.
Example 
6.
Matrix Metrics
7.
Frequently Asked Questions
7.1.
Is Matrix a data structure in R? 
7.2.
What is the difference between Matrix and Dataframe in R? 
7.3.
Can we convert a list to a matrix in R? 
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Matrices in R

Author Neha Chauhan
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

R is a programming language primarily used for statistical analysis and computing. With R programming, you can perform complex mathematical operations and statistical analysis and create high-quality plots and graphs. It is not just a programming language but an environment to implement statistical techniques.

Matrix in R programming is a rectangular arrangement of numbers. You can think of a matrix as a table with rows and columns or as a two-dimensional array that has rows and columns.  

A matrix in R Programming Language is a two-dimensional data structure. It is a homogeneous data structure i.e., you cannot store two different data types like - numbers and strings together in one matrix but you can store them in two different matrices. 

Matrix in R programming

In this article, we will discuss how to create, access and modify a matrix in R-programming language. 

Also see, Must Do Coding Questions

Creating a Matrix

There are two methods of creating a matrix in R programming; you can use the matrix() function to create a matrix and you can also create a matrix from a vector. 

Note: In r-programming, the indexing starts from 1. Consider the following example matrix -

 

1

2

3

1

10

50

90

2

20

60

100

3

30

70

110

4

40

80

120

Using matrix() function

You can use the matrix() function to create a matrix in R programming. By default, a matrix is filled column-wise however, this can be changed by using the arguments provided by the matrix() function.

Syntax

matrix(data, nrow, ncol, byrow, dimnames)  

 

This function has the following arguments: 

data - Enter the values to be filled in the matrix. 

nrow - the number of rows the matrix should contain

ncol - the number of columns the matrix should contain

byrow - by default it is set as FALSE. The matrix in R programming is filled column-wise, to fill the matrix row-wise set it to TRUE.  

dimnames - you can pass a 2-element list to the argument to set names for the rows and columns.

 

Example: Let’s create a 3x3 matrix with data - 1,2,3,4,5,6,7,8,9 

Code 

matrix(c(1,2,3,4,5,6,7,8,9),nrow=3, ncol=3)

Note: c() is a concatenate function, that is popularly used to create a one-dimensional vector. 

 

✅ Output:

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

Note: It is not necessary to provide both dimensions of the matrix. If one of the dimensions is present, the other dimension will be calculated from the length of the data. 

In the above example matrix, notice that the data has been filled column-wise. We will also discuss how to fill data row-wise later in this article.

Matrices in R are homogeneous data structures. If you try to add data of different data types R will automatically convert the data into the simplest data structure out of all the different data types available i.e. if you store values 1, 2.0 and ninja in a matrix R, will convert the data into a character data type. 

The rough order of data types is -  logical < integer < numeric < complex < character < list.

Also See, 8085 Microprocessor Pin Diagram

Using Vectors

In R programming, a vector is a sequence of the same type of data elements. We can use a vector as a matrix by setting the dimensions for the vector. 

Use the dim() function to set the dimensions for the vector to convert the vector into a matrix. 

Syntax 

dim() <- c(nrow, ncol) 

dim() is the dimensions function. 

c() is the concatenate function. 

nrow and ncol are number of rows and columns respectively.

 

Example 

Code 

Let’s create a 2x3 matrix with data 1,2,3,4,5,6

1️⃣ Start by creating a one-dimensional vector. 

Code

x <- c(1,2,3,4,5,6)
x

Note: x is a variable that we have created to store the vector. 

 

✅ Output

[1] 1 2 3 4 5 6

 

2️⃣ Using dim() set the dimensions for the vector. For our example, the dimensions will be 2,3 i.e. nrow will be 2 and ncol will be 3. 

Code

dim(x) <- c(2,3) 

✅ Output

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

Create a row-wise matrix

By default, the matrix in R programming is filled column-wise. 

We can fill the data row-wise by setting the byrow argument of the matrix() function to True. 

Syntax 

matrix(data, nrow, ncol, byrow = TRUE, dimnames)  

The explanation for the arguments has already been given in the section - using matrix() function.

 

Example 

Let’s create a 3x3 matrix with values - 1,2,3,4,5,6,7,8,9 

Code 

matrix(c(1,2,3,4,5,6,7,8,9), nrow=3, ncol=3, byrow=TRUE)

 

✅ Output

  [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

 

Recommended Topic, Cognizant Eligibility Criteria

Naming the rows and columns

You can give names to the rows and columns by passing a list holding two vectors to the dimnames argument of the matrix() function. One vector will be for the name of rows and another for name of columns. 

Creating new matrix with column and row names 

We can also create a matrix in R programming in which columns and rows have names. We can also give row and column names to an existing matrix.

Syntax

matrix(data, nrow, ncol, byrow, dimnames = list(c(), c()))

The explanation for the arguments has already been given in the section - using matrix() function.

Example 

Let's create a 2x3 matrix with rows and columns names as ‘row1’, ‘row2’ and ‘col1’, ‘col2’, ‘col3’ respectively. 

Code

matrix(c(1,2,3,4,5,6) , nrow = 2, ncol =3, dimnames = list(c("row1","row2"), c("col1","col2","col3")))

 

✅ Output

     col1 col2 col3
row1    1    3    5
row2    2    4    6

Assign names of rows and columns to an existing matrix 

You can also give names to the already existing matrices in R programming. Use the colnames() and rownames() functions to give names to the columns and rows of the existing matrix. 

Syntax 

colnames(matrix_name) <- c(column_names_values)

matrix_name is the variable in which you stored the matrix. 

column_names_values is comma-separated column names.  

 

rownames(matrix_name) <- c(row_names_values)

matrix_name is the variable in which you stored the matrix. 

row_names_values is comma-separated row names.  

 

Example 

Suppose we have a 3x3 matrix containing data 1,2,3,4,5,6,7,8,9 and let’s store it in a variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

 

Let’s name the rows and columns of this matrix as X, Y, Z and a, b, c respectively.  

Code

rownames(u) <- c("X","Y","Z")
colnames(u) <- c("a","b","c")

 

✅ Output

  a b c
X 1 4 7
Y 2 5 8
Z 3 6 9

Accessing Elements of a Matrix

You can access elements of a matrix in R Programming by using the number index, logical index and character indexes. 

Using Number Index

We can access elements of a matrix in R Programming by specifying the row and column numbers as vectors. 

Syntax

var[row, col]

Example 

Suppose we have the following 3x3 matrix stored in variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

🔼 Let’s say we want to view values of rows 1 and 2 and columns 1 and 2. 

Code

u [c(1,2), c(1,2)]

 

✅ Output

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

The output contains only 1st and 2nd row and column.

 

🔼 If any field is left blank, it will select all. 

Code

u[ ,c(1,2)] 

 

✅ Output

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

The output contains all the rows as the row field was left blank.

 

Code

u[c(2,3),] 

 

✅ Output

     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9

The output contains all the columns as the column field was left blank. 

 

🔼 You can use negative indexes to exclude a row or column. 

Code

u[c(-1), c(-1)] 

Or 

u[-1,-1]

 

✅ Output

     [,1] [,2]
[1,]    5    8
[2,]    6    9

The output excludes the 1st, row and column. 

 

🔼 You can also use a single index vector. While indexing in such a way, it acts like a vector formed by stacking columns of the matrix one after another. 

Code

u[1:4] 

 

✅ Output

[1] 1 2 3 4

 

Code

u[c(1,3,5,9)] 

 

✅ Output

[1] 1 3 5 9

Using logical vectors as an index

You can also use logical values as indexes. The place where the value is FALSE will be ignored and it will not be in the output. 

Syntax

var[row, col] 

 

Example 

Suppose we have the following 3x3 matrix stored in variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

Code

u[c(TRUE,FALSE,FALSE), c(FALSE,TRUE,TRUE)] 

 

✅ Output

[1] 4 7

Since the 2nd and 3rd row are set as FALSE and the 1st column is set as FALSE, the output will contain values of 1st row and 2nd & 3rd column. 

Using a Character vector as an index 

We can use the names of the matrix in R programming with named rows and columns to access the data. 

Syntax

var[row,col]

Example

Suppose we have the following 3x3 matrix stored in variable u

  a b c

X 1 4 7

Y 2 5 8

Z 3 6 9

Code

u[c(“X”,”Z”),c(“a”,”b”)]

 

✅ Output

  a b
X 1 4
Z 3 6

Modify a Matrix

You can also modify the value stored in the matrix in R programming and add new rows and columns for the matrix. Let’s discuss how to achieve that!

Modify the value stored

You can also change the values in the matrix. Use the <- operator with the methods to access the values. 

Example

Suppose we have the following 3x3 matrix stored in variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

Code

u[2,2] <- 100

 

✅ Output 

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    100    8
[3,]    3    6    9

You can use any above-mentioned methods used for accessing the values and combine them with <- operator to modify the values stored in the matrix. 

Add new rows or columns 

You can add new rows and columns to the existing matrix using the rbind() and cbind() functions respectively. 

Syntax

cbind(matrix_name,vector_list)
rbind(matrix_name,vector_list) 

Example 

Suppose we have the following 3x3 matrix stored in variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

🔼 Let’s add a new row with values 10, 20, 30

Code

rbind(u, c(10,20,30))

 

✅ Output

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[4,]   10   20   30

 

🔼 Let’s add a new row with values 100, 200, 300.

Code

cbind(u, c(100,200,300))

 

✅ Output

     [,1] [,2] [,3] [,4]
[1,]    1    4    7  100
[2,]    2    5    8  200
[3,]    3    6    9  300

Modifying dimensions 

We can also modify the dimensions of the matrices in R programming by using the dim() function. 

Syntax

dim(matrix_name) <- new_dimensions

Example 

Suppose we have the following 2x3 matrix stored in variable u -

      col1 col2 col3

row1    1    3    5

row2    2    4    6

Code  

dim(u) <- c(3,2) 

 

✅ Output

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

Notice that the names of the rows and columns of the matrix have been changed. 

Matrix Metrics

There are many functions that will help you in determining information about the matrices in R programming, like the dimensions or number of elements in the matrix. 

Suppose we have the following 3x3 matrix stored in variable u

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

[1,]    1    4    7

[2,]    2    5    8

[3,]    3    6    9

🔼 Use the dim() function to determine the dimensions of the matrix. 

Code

dim(u) 

 

✅ Output 

[1] 3 3

 

🔼 Use the nrow() and ncol() functions to determine the number of rows and columns respectively.

Code

nrow(u) 

 

✅ Output

[1] 3

 

Code

ncol(u)

 

✅ Output

[1] 3

 

🔼 Use the class() function to determine the type of object. 

Code

class(u) 

 

✅ Output

[1] "matrix" "array" 


You can also read about mock interview.

Frequently Asked Questions

Is Matrix a data structure in R? 

Yes. Matrices in R programming are a 2-dimensional data structure that has row and column attributes. It is a homogeneous data structure i.e. it can store the same kind of data. 

What is the difference between Matrix and Dataframe in R? 

Matrices in R programming are a homogeneous data structure that can store a single type of data while a data frame is a table with different types of data inside it.

Can we convert a list to a matrix in R? 

Yes. A list with vectors that hold an even number of elements can be converted into a matrix. To do this use the unlist() function inside the matrix() function like this - matrix(unlist(list_to_be_converted), ncol, nrow). 

Conclusion

Pat yourself on the back for finishing this article. In this article, we have discussed various methods to create a matrices in R programming. We have also discussed how to access the elements of matrices in R programming and how to modify them. At the end of the article, we discussed about the methods to determine the metrics of the matrices in R programming. 

Check out this problem - Matrix Median

Do not stop learning! We recommend you read these articles - 

🔥 Resume for software engineer fresher

🔥 Best Data Science Certification

🔥 Data Science Associate at ZS

🔥 Data Analyst vs Data Scientist

Head to the Guided Path on the Coding Ninjas Studio and upskill in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more courses.

If you want to Practice top Coding Problems, attempt mock tests, or read interview experiences, head to the Coding Ninjas Studio, our practice platform.

We wish you Good Luck!🎈 Please upvote our blog 🏆 and help other ninjas grow.

Live masterclass