The Wayback Machine - https://web.archive.org/web/20240828110754/https://www.geeksforgeeks.org/r-matrices/
Open In App

R – Matrices

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

R-matrix is a two-dimensional arrangement of data in rows and columns.

In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices:

R - MatricesGeeksforgeeks

R – Matrices

Creating a Matrix in R

To create a matrix in R you need to use the function called matrix().

The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix.

Note: By default, matrices are in column-wise order.

Syntax to Create R-Matrix

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

Parameters:

  • data – values you want to enter
  • nrow – no. of rows
  • ncol – no. of columns
  • byrow – logical clue, if ‘true’ value will be assigned by rows
  • dimnames – names of rows and columns

Example:

R
# R program to create a matrix
 
A = matrix(
    
  # Taking sequence of elements  
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  
  # No of rows
  nrow = 3,   
  
  # No of columns
  ncol = 3,         
  
  # By default matrices are in column-wise order
  # So this parameter decides how to arrange the matrix
  byrow = TRUE          
)
 
# Naming rows
rownames(A) = c("a", "b", "c")
 
# Naming columns
colnames(A) = c("c", "d", "e")
 
cat("The 3x3 matrix:\n")
print(A)

Output
The 3x3 matrix:
  c d e
a 1 2 3
b 4 5 6
c 7 8 9

Creating Special Matrices in R

R allows the creation of various different types of matrices with the use of arguments passed to the matrix() function.

1. Matrix where all rows and columns are filled by a single constant ‘k’: 

To create such a R matrix the syntax is given below:

Syntax: matrix(k, m, n)

Parameters: 
k: the constant 
m: no of rows 
n: no of columns 

Example: 

R
# R program to illustrate
# special matrices

# Matrix having 3 rows and 3 columns
# filled by a single constant 5
print(matrix(5, 3, 3)) 

Output
     [,1] [,2] [,3]
[1,]    5    5    5
[2,]    5    5    5
[3,]    5    5    5

2. Diagonal matrix: 

A diagonal matrix is a matrix in which the entries outside the main diagonal are all zero. To create such a R matrix the syntax is given below:

Syntax: diag(k, m, n)
Parameters: 
k: the constants/array 
m: no of rows 
n: no of columns  

Example: 

R
# R program to illustrate
# special matrices

# Diagonal matrix having 3 rows and 3 columns
# filled by array of elements (5, 3, 3)
print(diag(c(5, 3, 3), 3, 3)) 

Output
     [,1] [,2] [,3]
[1,]    5    0    0
[2,]    0    3    0
[3,]    0    0    3

3. Identity matrix: 

An identity matrix in which all the elements of the principal diagonal are ones and all other elements are zeros. To create such a R matrix the syntax is given below:

Syntax: diag(k, m, n)
Parameters: 
k: 1 
m: no of rows 
n: no of columns 

Example: 

R
# R program to illustrate
# special matrices

# Identity matrix having
# 3 rows and 3 columns
print(diag(1, 3, 3)) 

Output
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

4. Matrix Metrics

Matrix metrics tell you about the Matrix you created. You might want to know the number of rows, number of columns, dimensions of a Matrix.

Below Example will help you in answering following questions:

  • How can you know the dimension of the matrix?
  • How can you know how many rows are there in the matrix?
  • How many columns are in the matrix?
  • How many elements are there in the matrix?

Example: 

R
# R program to illustrate
# matrix metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

cat("Dimension of the matrix:\n")
print(dim(A))

cat("Number of rows:\n")
print(nrow(A))

cat("Number of columns:\n")
print(ncol(A))

cat("Number of elements:\n")
print(length(A))
# OR
print(prod(dim(A)))

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Dimension of the matrix:
[1] 3 3
Number of rows:
[1] 3
Number of columns:
[1] 3
Number of elements:
[1] ...

Accessing Elements of a R-Matrix

We can access elements in the R matrices using the same convention that is followed in data frames. So, you will have a matrix and followed by a square bracket with a comma in between array.

Value before the comma is used to access rows and value that is after the comma is used to access columns. Let’s illustrate this by taking a simple R code.

Accessing rows: 

R
# R program to illustrate
# access rows in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Accessing first and second row
cat("Accessing first and second row\n")
print(A[1:2, ])

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Accessing first and second row
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Accessing columns: 

R
# R program to illustrate
# access columns in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Accessing first and second column
cat("Accessing first and second column\n")
print(A[, 1:2])

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Accessing first and second column
     [,1] [,2]
[1,]    1    2
[2,]    4    5
[3,]    7    8

More Example of Accessing Elements of a R-matrix: 

R
# R program to illustrate
# access an entry in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Accessing 2
print(A[1, 2])

# Accessing 6
print(A[2, 3])

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[1] 2
[1] 6

Accessing Submatrices in R:

We can access the submatrix in a matrix using the colon(:) operator. 

R
# R program to illustrate
# access submatrices in a matrix

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

cat("Accessing the first three rows and the first two columns\n")
print(A[1:3, 1:2])

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Accessing the first three rows and the first two columns
     [,1] [,2]
[1,]    1    2
[2,]    4    5
[3...

Modifying Elements of a R-Matrix

In R you can modify the elements of the matrices by a direct assignment. 

Example: 

R
# R program to illustrate
# editing elements in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Editing the 3rd rows and 3rd column element
# from 9 to 30
# by direct assignments
A[3, 3] = 30

cat("After edited the matrix\n")
print(A)

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
After edited the matrix
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8   30

R-Matrix Concatenation

Matrix concatenation refers to the merging of rows or columns of an existing R matrix. 

Concatenation of a row: 

The concatenation of a row to a matrix is done using rbind(). 

R
# R program to illustrate
# concatenation of a row in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Creating another 1x3 matrix
B = matrix(
  c(10, 11, 12),
  nrow = 1,
  ncol = 3
)
cat("The 1x3 matrix:\n")
print(B)

# Add a new row using rbind()
C = rbind(A, B)

cat("After concatenation of a row:\n")
print(C)

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
The 1x3 matrix:
     [,1] [,2] [,3]
[1,]   10   11   12
After concatenation of a row:
     [,1] [,2] [,3...

Concatenation of a column: 

The concatenation of a column to a matrix is done using cbind(). 

R
# R program to illustrate
# concatenation of a column in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Creating another 3x1 matrix
B = matrix(
  c(10, 11, 12),
  nrow = 3,
  ncol = 1,
  byrow = TRUE
)
cat("The 3x1 matrix:\n")
print(B)

# Add a new column using cbind()
C = cbind(A, B)

cat("After concatenation of a column:\n")
print(C)

Output
The 3x3 matrix:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
The 3x1 matrix:
     [,1]
[1,]   10
[2,]   11
[3,]   12
After concatenation of a column:
     [,1] [,2] ...

Dimension inconsistency: Note that you have to make sure the consistency of dimensions between the matrix before you do this matrix concatenation. 

R
# R program to illustrate
# Dimension inconsistency in metrics concatenation

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("The 3x3 matrix:\n")
print(A)

# Creating another 1x3 matrix
B = matrix(
  c(10, 11, 12),
  nrow = 1,
  ncol = 3,
)
cat("The 1x3 matrix:\n")
print(B)

# This will give an error 
# because of dimension inconsistency
C = cbind(A, B)

cat("After concatenation of a column:\n")
print(C)

Output: 

The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
The 1x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 10 11 12
Error in cbind(A, B) : number of rows of matrices must match (see arg 2)

Adding Rows and Columns in a R-Matrix

To add a row in R-matrix you can use rbind() function and to add a column to R-matrix you can use cbind() function.

Adding Row

Let’s see below example on how to add row in R-matrix?

Example:

R
# Create a 3x3 matrix
number <- matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("Before inserting a new row:\n")
print(number)

# New row to be inserted
new_row <- c(10, 11, 12)  # Define the new row

# Inserting the new row at the second position
A <- rbind(number[1, ], new_row, number[-1, ])

cat("\nAfter inserting a new row:\n")
print(number)

Output
Before inserting a new row:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

After inserting a new row:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]...

Adding Column

Let’s see below example on how to add column in R-matrix?

R
# Create a 3x3 matrix
number <- matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("Before adding a new column:\n")
print(number)

# New column to be added
new_column <- c(10, 11, 12)  # Define the new column

# Adding the new column at the end
number <- cbind(number, new_column)

cat("\nAfter adding a new column:\n")
print(number)

Output
Before adding a new column:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

After adding a new column:
           new_column
[1,] 1 2 3         10
[2,] 4 5 6         1...

Deleting Rows and Columns of a R-Matrix

To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. 

Row deletion: 

R
# R program to illustrate
# row deletion in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("Before deleting the 2nd row\n")
print(A)

# 2nd-row deletion
A = A[-2, ]

cat("After deleted the 2nd row\n")
print(A)

Output
Before deleting the 2nd row
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
After deleted the 2nd row
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    7    8    9

Column deletion:  

R
# R program to illustrate
# column deletion in metrics

# Create a 3x3 matrix
A = matrix(
  c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
  nrow = 3,             
  ncol = 3,             
  byrow = TRUE          
)
cat("Before deleting the 2nd column\n")
print(A)

# 2nd-row deletion
A = A[, -2]

cat("After deleted the 2nd column\n")
print(A)

Output
Before deleting the 2nd column
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
After deleted the 2nd column
     [,1] [,2]
[1,]    1    3
[2,]    4    6
[3,]    7    9

We have discussed the about R-matrices and their basic operations like adding new rows and columns, deleting rows and columns, merging matrices,etc.

Hope this helped you in understanding matrices in R, and you can now comfortably use R-matrices in your projects.

Also Check:



Previous Article
Next Article

Similar Reads

Combining Matrices in R
Combining matrices involves the concatenation of two or more smaller matrices, either row or column wise to form a larger matrix. It is basically a data manipulation operation where the involved matrices must be of compatible sizes to execute the operation. Matrices can be combined either horizontally or vertically. There are two ways of combining
3 min read
How to load and modify matrices and vectors in Octave?
In this article, we will see how to load and play with the data inside matrices and vectors in Octave. Here are some basic commands and function to regarding with matrices and vector in Octave : 1. The dimensions of the matrix : We can find the dimensions of a matrix or vector using the size() function. C/C++ Code % declaring the matrix M = [1 2 3;
6 min read
Working with Sparse Matrices in R Programming
Sparse matrices are sparsely populated collections of elements, where there is a very less number of non-null elements. Storage of sparsely populated data in a fully dense matrix leads to increased complexities of time and space. Therefore, the data structures are optimized to store this data much more efficiently and decrease the access time of el
9 min read
Fixing Non Positive Definite Correlation Matrices Using R
In this article we will discuss Fixing non-positive definite correlation matrices using R Programming Language, The correlation matrices are fundamental tools in various statistical analyses and structural equation modeling, and portfolio optimization. These matrices represent relationships between different variables and can be expected to have ce
4 min read
Merge two matrices by row names in R
In this article, we will examine various methods to merge two matrices by row names in the R programming language. What is a matrix?A matrix is defined as it is a two-dimensional data set which is the collection of rows and columns. A matrix can have the ability to contain or accept data of the same type such as integers, characters, floating point
4 min read
Operations on Matrices in R
Matrices in R are a bunch of values, either real or complex numbers, arranged in a group of fixed number of rows and columns. Matrices are used to depict the data in a structured and well-organized format. It is necessary to enclose the elements of a matrix in parentheses or brackets. A matrix with 9 elements is shown below. [Tex]\begin{bmatrix}1
8 min read
Ruby Programming Language
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer betwe
2 min read
Golang
Golang is a procedural and statically typed programming language having the syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It provides a rich standard library, garbage collection, and dynamic-typing capability. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launch
2 min read
Kotlin Tutorial
This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In This free Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collections, and more. We will also delve into advanc
5 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Python for Kids - Fun Tutorial to Learn Python Programming
Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzles, Python provides the foundation to the kids or a
15+ min read
Frequency table in R
In this article, we are going to learn how to make a frequency table in the R programming language. Table of ContentFrequency TableOne-Way Frequency Tables in RTwo-Way Frequency Tables in RFrequency TableA frequency table is a list of objects with the frequency of each item shown in the table. When evaluating categorical data to determine how frequ
5 min read
7 Best IDEs For C/C++ Developers in 2024
Everything has been digitized in this digital era, and nothing seems possible without programming. The fact that C is the building block of all the programming languages can't be denied. Also, the extended version of C is C++, which you can call a subset of C. Every one of us must have gone through the basic concepts of this language before steppin
8 min read
Top 10 Fastest Programming Languages
There are approximately 700 programming languages in the world. In simple words, a programming language is used to give instructions to the computer to perform the task which we require. Have you ever wondered which is the fastest of all the programming languages in terms of execution speed? In most cases, speed is not the only metric to choose whi
8 min read
R Tutorial | Learn R Programming Language
R Programming Tutorial is designed for beginners and experts. This free R Tutorial gives you knowledge basic to advanced of concepts of the R programming language. Here you will get a detailed introduction, features, installation, variables, data types, operators, if statements, vectors, data handling, graphics, and statistical modeling of R progra
9 min read
Advantages and Disadvantages of OOP
OOP stands for Object-Oriented Programming. As you can guess from it's name it breaks the program on the basis of the objects in it. It mainly works on Class, Object, Polymorphism, Abstraction, Encapsulation and Inheritance. Its aim is to bind together the data and functions to operate on them. Some of the well-known object-oriented languages are O
3 min read
Difference between Shallow and Deep copy of a class
Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep C
5 min read
Top 20 Programming Languages to Learn in 2024: A Complete List for Developers
Are you wondering which programming languages will dominate the tech world in 2024? Curious about which skills will be most in demand by employers? Or perhaps you're trying to figure out which programming language is the best fit for your career growth? The answers to these questions are more critical now than ever, as the right choice can shape th
15+ min read
Introduction of Object Oriented Programming
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of
6 min read
Extract text from PDF File using Python
All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. We will extract text from pdf files using two Pytho
5 min read
R Programming Language - Introduction
The R Language stands out as a powerful tool in the modern era of statistical computing and data analysis. Widely embraced by statisticians, data scientists, and researchers, the R Language offers an extensive suite of packages and libraries tailored for data manipulation, statistical modeling, and visualization. In this article, we explore the fea
7 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Increment and Decrement Operators in C
The increment ( ++ ) and decrement ( -- ) operators in C are unary operators for incrementing and decrementing the numeric values by 1 respectively. The incrementation and decrementation are one of the most frequently used operations in programming for looping, array traversal, pointer arithmetic, and many more. In this article, we will discuss the
4 min read
Control Structures in Programming Languages
Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of l
3 min read
Structures in C++
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non
5 min read
Differences between Procedural and Object Oriented Programming
This article focuses on discussing the differences between procedural and object-oriented programming. Procedural Programming Procedural Programming can be defined as a programming model which is derived from structured programming, based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply con
2 min read
Introduction to Programming Languages
Introduction: A programming language is a set of instructions and syntax used to create software programs. Some of the key features of programming languages include: Syntax: The specific rules and structure used to write code in a programming language.Data Types: The type of values that can be stored in a program, such as numbers, strings, and bool
13 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it returns a new type object. Python type() function Sy
5 min read
Python String format() Method
The format() method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex
13 min read