R Matrix

In this tutorial you will learn about the R Matrix and its application with practical example.

R Matrix

Matrix is a two dimensional data structure, where elements are arranged in rows and columns. It can thought as combination of two or more vectors of same data type. Following is an example of a 2×4 matrix with 2 rows and 4 columns.

r_matrix_example

Creating a Matrix

A matrix is created using the matrix() function. The values for matrix rows and matrix columns is defined using nrow and ncol arguments. However, it is not required to provide value for both as it automatically evaluate the value for other dimension using length of matrix.

Syntax:-

Above is the general syntax of matrix() function, here

data:- It is a vector input which will arranged as matrix.
nrow:- Number of rows.
ncol:- Number of columns.
byrow:- If it is TRUE values being filled by row (left to right). If it is FALSE values being filled by Column(top to bottom). Default is FALSE.

Example:-

Here we are creating two 5×2 matrix which contains number from 1 to 10 keeping byrow = TRUE for and byrow = FALSE for other to check the difference.

Output:-

r_creating_matrix

Accessing Matrix Element

Matrix elements can be accessed by using the row and column index of the element as following –

Syntax:-

matrix:- Matrix name
row:- row index of the element, if not provided specified row elements will be fetched for all columns.
col:- column index of the element, if not provided specified column elements will be fetched for all rows.

Example:-

Let’s have a 3×5 matrix which contains number from 1 to 15 keeping byrow = TRUE. Now, we are accessing different matrix elements as following –

When we run the above R script, we see the following output –

Output:-

r_access_matrix_elements

Update Matrix Element

A matrix element can be modified by accessing element using above method and assigning it new value.

Example:-

Output:-

r_update_matrix_element

Matrix rbind() and cbind() Function

The rbind() and cbind()function is used to add a row and column respectively to a matrix.

Example:-

Output:-

r_matrix_cbind_rbind

R Transpose a Matrix

The t() function is used to transpose a matrix.

Example:-

Output:-

r_transpose_matrix

In this tutorial we have learn about the R Matrix and its application with practical example. I hope you will like this tutorial.