Open In App

How to create a matrix in R

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss What is a matrix and various methods to create a matrix by using R Programming Language.

What is a matrix?

A matrix is a two-dimensional data set that collects rows and columns. The matrix stores the data in rows and columns format. It is possible to access the data in the matrix easily.

How to create the matrix

R language offers various methods to create a matrix efficiently. By using these methods provided by R, it is easy to create the matrix. Some of the methods to create the matrix are:

Creating a matrix by using the function ‘matrix()’

These is the one of the common method used by the users to create the matrices in R language. These function ‘matrix()’ can allows us to access the data elements and can able to specify the dimension of matrix.

matrix(data)

In the below example, we created the simple matrix by using the function ‘matrix()’.

R
# Creating a matrix with predefined data
matrix_data <- matrix(c(1,2,3,4,5,6,7,8,9),3,3)

print(matrix_data)

Output:

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

In the below example, we created the matrix with single input of data by using the function ‘matrix()’.

R
#data
x=10

#creating the matrix
matrix=matrix(x, nrow=5,ncol=5)

print("The matrix is")
print(matrix)

Output:

[1] "The matrix is"

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

Creating matrix by using the function ‘rbind()’

rbind() stands for row bind in which the main aim is used to combine matrices, vectors and data frames by rows. It can able to create matrices by using the vectors .

The syntax is as follows:

rbind(vec1,vec2.....vec n)

In the below example, we created the matrix by using the function ‘rbind()’.

R
a=c(1,2,3,4,5,6,7)
b=c(35, 36, 37, 38, 39, 40, 41)
c=c( 92, 93, 94, 95, 96, 97, 98)

#creating matrix
matrix=rbind(a,b,c)
print("The matrix is")
print(matrix)

Output:

[1] "The matrix is"

[,1] [,2] [,3] [,4] [,5] [,6] [,7]
a 1 2 3 4 5 6 7
b 35 36 37 38 39 40 41
c 92 93 94 95 96 97 98

Now we create one alfabetically matrix using rbind() function.

R
w=c("m","a","h","e","s","h")             
x=letters[1:6]                           
y=c("l","o","k","e","s","h")            
z=letters[7:12]   

#creating matrix
matrix=rbind(w,x,y,z)

print("The matrix is")
print(matrix)

Output:

[1] "The matrix is"

[,1] [,2] [,3] [,4] [,5] [,6]
w "m" "a" "h" "e" "s" "h"
x "a" "b" "c" "d" "e" "f"
y "l" "o" "k" "e" "s" "h"
z "g" "h" "i" "j" "k" "l"

Conclusion

In Conclusion, we learned about how to create matrix by using various methods in R. R language offers versatile tools for creating the matrices efficiently.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads