Matrices in R Programming – The Ultimate Guide

What are Matrices?

Matrices are the R objects wherein the elements are organized in a 2-D rectangular shape. In a matrix, it contains elements of the same atomic types.

The matrix function is denoted as a matrix().

Syntax

matrix(data, nrow, ncol, byrow, dimnames)
  • data is the parameter of input,
  • nrow is number of rows and
  • ncol is the number of columns to be created;
  • byrow has TRUE or FALSE as its logical values, and dimname is the rows or columns name.
    Excel in Every Aspect of Data Science
    Transform Through Our Data Science Training
    quiz-icon

Accessing Elements of a matrix

Any row or column element can be accessed by using the column and row index.

Example:

#Defining the column and row names
rn = c("r1", "r2", "r3", r4")
cn = c("c1", "c2", "c3")
#Creating the matrix
A <- matrix(c(1:12), nrow = 4, byrow = TRUE, dimnames= list(rn, cn))
#Accessing 2nd row, 3rd column element
print(A[2,3])
#Accessing  elements of 4th column
print(A[ ,4])

Output:

[1] 6 
row1  row2  row3  row4
   3        6          9        12

Matrix Computations

Different types of mathematical operations such as matrix addition, subtraction, multiplication, and division can be performed on the matrices using R Programming operators.

To learn in depth, we recommend you our amazing Data Science certification course.
 

Related Blogs What’s Inside
Data Mining vs Data Science Highlights data mining and data science differences in goals and methods.
How to Pass the Google Data Engineer Certification Offers advice for succeeding in the Google Data Engineer certification.
Data Structures in R Programming Explains R data structures like data frames for data tasks.
Data Science vs Software Engineering Explores data science versus software engineering in career scope.
Autoencoders in Deep Learning Details autoencoders for feature learning in deep learning systems.
Top Data Science Companies in India Details top Indian firms offering data science career paths.
Data Science Prerequisites Describes essential prerequisites for a data science career.
What is AutoSum? Describes Excel’s AutoSum tool for rapid data calculations.
Data Science vs Computer Science Outlines data science and computer science differences in roles.
Strings in R Programming Highlights string processing in R for text data tasks.
Introduction to Data Science Explains data science basics and its industry relevance for beginners.
R Studio Showcases R Studio’s features for R programming and data tasks.

About the Author

Principal Data Scientist, Accenture

Meet Akash, a Principal Data Scientist with expertise in advanced analytics, machine learning, and AI-driven solutions. With a master’s degree from IIT Kanpur, Aakash combines technical knowledge with industry insights to deliver impactful, scalable models for complex business challenges.