ADVERTISEMENT
ADVERTISEMENT

Matrices in R Language

R | Matrices: In this tutorial, we are going to learn about the matrices, creating a matrix in r, accessing the matrix elements, matrix transformation, etc. with examples.
Submitted by Bhavya Sri Khandrika, on December 13, 2020

In the earlier articles, we have come across the basic entities that are widely employed while working with the R language. Several types of data types are predefined in the R environment. On listing them we find the below data types:

  • Vectors
  • Lists
  • Matrices
  • Arrays
  • Factors
  • Data frames

In the previous articles, we have covered Vectors and lists. Here, we will discuss Matrices.

Matrices are the R-objects that store elements in them. But the orientation of storing the elements vary in their dimensions. In case if the elements are stored in a two-dimensional rectangular layout then we usually call it a matrix. Matrices contain elements of the same type i.e., the elements stored in them are homogeneous in nature. But however, such matrices are not used widely. Such matrices have their own limitations. The matrices with the numeric values are broadly used in the calculations. The elements present in the matrix are real numbers. Using the matrix function, an individual can effortlessly reproduce the memory required for the matrix.

Creating a Matrix

Syntax:

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

Parameters used:

  • data is the input vector which later becomes the data elements of the designed matrix.
  • nrow is the number of rows of the matrix
  • ncol is the number of columns of the matrix
  • byrow is the logical clue. If the result of it is TRUE then the elements will be arranged in the row.
  • dimnames pertains to the names allocated to the rows as well as the columns in the matrix.

Program 1:

#  In this case the Elements are 
# classified successively by row.

M <- matrix(c(1:12), nrow = 4, byrow = TRUE)

print(M)

Output:

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

In the above code, the elements are arranged sequentially with the help of row numbers.

Program 2:

# Here the Elements are organized 
# consecutively by column.

N <- matrix(c(1:9), nrow = 3, byrow = FALSE)

print(N)

Output:

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

In the above code, the columns are considered and thus are arranged sequentially by columns.

Program 3:

# Defining the column and row names and 
# then displaying the declared elements.
rownames = c("r1", "r2", "r3")
colnames = c("c1", "c2", "c3")

P <- matrix(c(5:13), nrow = 3, byrow = TRUE, dimnames = list(rownames, colnames))

print(P)

Output:

          c1 c2 c3
r1       5   6   7
r2       8   9   10
r3       11  12  13

In the above code, we have successfully created the matrix and declared the elements in it.

Accessing the Matrix elements

One must be well acquainted with the various types of accessing the elements in the matrix. In the R language, we can access matrix elements with the help of the index numbers. There are three ways to access the matrix elements in the R language. All of them are stated below:

Accessing the elements present in the mth column and the nth row:

  • Step 1: Define the column and row names in the matrix with the names of the row and column.
  • Step 2: Creating a matrix with the elements in it.
  • Step 3: Access the element present on the 2nd row and the 3rd column.

Code:

row_names = c("r1", "r2", "r3", "r4") 
col_names = c("c1", "c2", "c3") 

R <- matrix(c(1:12), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names)) 

print(R) 

print(R[2,3]) 

Output:

    c1   c2  c3
r1  1    2   3
r2  4    5   6
r3  7    8   9
r4  10  11  12
[1] 6

Accessing all elements present in a particular row, i.e. at the nth row Or in a particular column i.e. at the mth column.

Example:

  • Step 1: Defining the column and row names in the matrix.
  • Step 2: Creating a matrix with the elements in it.
  • Step 3: Accessing the element present in the 2nd-row.
  • Step 3: Accessing the element present in the 3rd column.

Code:

row_nam = c("r_1", "r_2", "r_3", "r_4")  
col_nam = c("c_1", "c_2", "c_3")  

A <- matrix(c(2:13), nrow = 4, byrow = TRUE, dimnames = list(row_nam, col_nam))  

print(A)  

print(A[2,])

print(A[, 3])

Output:

       c_1 c_2 c_3
r_1     2   3   4
r_2     5   6   7
r_3     8   9  10
r_4    11  12  13
    c_1   c_2   c_3 
    5      6      7
r_1   r_2   r_3   r_4 
   5      8      11    14

Modifications on the matrices

The R language provides three ways of modifying the data present in the matrices. They are as follows:

Assign a single element:

In matrix transformation, the initial technique is to allocate a single element to the matrix at a specific position. By allotting a different value to that place, the former number will get renovated with the recent one.

Syntax:

matrix[n, m]<-y

Here, n and m represent the number of rows and columns respectively. The y is the value that we assign externally in order to modify the matrix already present.

  • Step 1: Define the column and row names in the matrix.
  • Step 2: Construct the matrix with the elements.
  • Step 3: Assigning value 20 to the element at 2nd row and 2nd column.

Code:

  • Step 1: Define the row and column names in the matrix.
  • Step 2: Assign the value 20 at the 2nd row and 3rd column.
row_nam = c("r1", "r2", "r3", "r4")  
col_nam = c("c1", "c2", "c3")  

A <- matrix(c(1:12), nrow = 4, byrow = TRUE, dimnames = list(row_nam, col_nam))  

print(A)  

A[2,3]<-20  

print(A)

Output:

  c1 c2 c3
r1  1  2  3
r2  4  5  6
r3  7  8  9
r4 10 11 12
   c1 c2 c3
r1  1  2  3
r2  4  5 20
r3  7  8  9
r4 10 11 12

By using the relational operators:

The other way of modifying the matrices is to use the relational operators. The use of relational operators like <, >, >=, <=, == will help the programmer in modifying the contents of the matrix.

  • Step 1: Define the column and row names of the matrix considered.
  • Step 2: Initialization of the matrix with several elements.
  • Step 3: Replacing all the elements whose values are bigger than 8.

Code:

row_names = c("r1", "r2", "r3", "r4")  
col_names = c("c1", "c2", "c3")  

C <- matrix(c(1:12), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))  

print(C)  

C[C>8]<-0  

print(C) 

Output:

    c1 c2 c3
r1  1  2  3
r2  4  5  6
r3  7  8  9
r4  10 11 12
    c1 c2 c3
r1  1  2  3
r2  4  5  6
r3  7  8  0
r4  0  0  0

Matrix Transformation

The third technique of matrix transformation is with the help of the proliferation of rows and columns with the help of the cbind() and rbind() function. The cbind() and rbind() functions are widely utilized in the case when the programmer wishes to add columns and rows respectively. To understand the working of cbind() and rbind() function let us consider a simple example shown below:

  • Step 1: Defining the columns and rows and giving them names in a matrix.
  • Step 2: Initializing the matrix with different numeric values.
  • Step 3: Addition of an extra row to the matrix.
  • Step 4: Addition of the extra column to the considered matrix
  • Step 5: Finding the transpose of the considered matrix with the help of t() function.
  • Step 6: Modify the dimensions of the assessed matrix with the help of the dim() function.

Code:

row_names = c("r1", "r2", "r3", "r4")  
col_names = c("c1", "c2", "c3")  

K <- matrix(c(4:15), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))  

print(K)  

rbind(K,c(16,17,18))  
cbind(K, c(1,2,3,4))  

t(K)  

dim(K)<-c(2,6)  

print(K)

Output:

    c1 c2 c3
r1  4  5  6
r2  7  8  9
r3 10 11 12
r4 13 14 15
    c1 c2 c3
r1  4  5  6
r2  7  8  9
r3 10 11 12
r4 13 14 15
16 17 18
    c1 c2 c3  
r1  4  5  6 1
r2  7  8  9 2
r3 10 11 12 3
r4 13 14 15 4
    r1 r2 r3 r4
c1  4  7 10 13
c2  5  8 11 14
c3  6  9 12 15
[,1] [,2] [,3] [,4] [,5] [,6]
[1,]    4   10    5   11    6   12
[2,]    7   13    8   14    9   15

Matrix Operations

In R, one can accomplish the mathematical calculations on a matrix such as addition, subtraction, division, multiplication, etc. For executing the mathematical operations on the matrix, it is very mandatory that both the matrices should have identical dimensions.

Here is a sample code that demonstrates the execution of the above-stated operations or manipulations on the matrix considered.

  • Step 1: Create a matrix with the declared dimensions.
  • Step 2: Addition Of the two vectors considered.
  • Step 3: Subtraction of the Two vectors taken.
  • Step 4: Multiplication Of both vectors mul<-B*C.
  • Step 5: Multiplication by a constant.
  • Step 6: Division of the two vectors.

Code:

B<- matrix(c(6:17), nrow = 4,ncol=3)  
C<- matrix(c(3:14), nrow = 4,ncol=3)  

sum<-B+C 
print(sum)  

sub<- B-C  
print(sub)  

mul <- B*C
print(mul)  

mul1<-B*6 
print(mul1)  

div<-B/C  
print(div) 

Output:

     	[,1] [,2] [,3]
[1,]    9   17   25
[2,]   11   19   27
[3,]   13   21   29
[4,]   15   23   31
     	[,1] [,2] [,3]
[1,]    3    3    3
[2,]    3    3    3
[3,]    3    3    3
[4,]    3    3    3
     	[,1] [,2] [,3]
[1,]   18   70  154
[2,]   28   88  180
[3,]   40  108  208
[4,]   54  130  238
     	[,1] [,2] [,3]
[1,]   36   60   84
[2,]   42   66   90
[3,]   48   72   96
[4,]   54   78  102
     	[,1]     [,2]     [,3]
[1,] 	2.00 1.428571 1.272727
[2,] 	1.75 1.375000 1.250000
[3,] 	1.60 1.333333 1.230769
[4,] 	1.50 1.300000 1.214286

Here are the major applications of these matrices,

Applications of the matrices

  1. In geology, Matrices carries surveys and designs the several types of graphs, statistics based on the information that is gathered through surveys. And further, it is widely utilized to research in different fields.
  2. Matrix is the presentation technique that assists in designing formal survey things.
  3. If we consider the field of robotics and automation, One can observe that matrices have the best elements for robot actions.
  4. Matrices are largely employed in evaluating the entire household commodities in Economics, and in addition to that, it also assists in evaluating the ability of goods and merchandise.
  5. When we consider computer-based applications, One can largely observe the matrices playing a significant role in the innovation of logical seeming gestures.
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.