Working with Matrix in R programming

We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

If we want to store data of same mode or type in a two-dimensional array in R data analysis, matrix may be the most appropriate data structure to use. A matrix is just coming from a vector expanded in two dimensions with rows and columns, this is why the input subject is often a vector when a matrix is generated.

  1. Generating a matrix

Function matrix() can be used to generate a new matrix in R. The general format for this function is :

NewMatrix <- matrix(INPUT, nrow=n_rows, ncol=n_columns,
byrow=YES/NO, dimnames=list(
rownames, colnames))

where INPUT is usually a vector which contains the elements to be transformed to the elements new matrix, and nrow and ncol specify how many rows and
columns the new matrix has. Option ‘by row’ means the element from INPUT will be arranged rowwise (byrow=TRUE) or columnwise (byrow=FALSE). The default value for this option is by column, and the option of dimnames allow the specification of row and column labels for the matrix. Following code snippet show how three different matrices are created using matrix() function with their particular options.

#a matrix y is created, having 30 elements, arranged by 
# column
> y <- matrix(1:30, nrow = 5, ncol = 6) 
> y
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    6   11   16   21   26
[2,]    2    7   12   17   22   27
[3,]    3    8   13   18   23   28
[4,]    4    9   14   19   24   29
[5,]    5   10   15   20   25   30

> input <- c(31, 36, 34, 68)
> rowname <- c("N1", "N2")
> colname <- c("L1", "L2")
> 
#2 × 2 matrix filled by rows
> NewMatrix1 <- matrix(input,
+   nrow = 2, ncol = 2, byrow = TRUE,
+   dimnames = list(rowname, colname))
> 
> NewMatrix1
   L1 L2
N1 31 36
N2 34 68
#2 × 2 matrix filled by column
> NewMatrix2 <- matrix(input,
+   nrow = 2, ncol = 2, byrow = FALSE,
+   dimnames = list(rowname, colname))
> 
> NewMatrix2
   L1 L2
N1 31 34
N2 36 68

Note that when a command covers more than two rows , RStudio will automatically show a plus symbol + at the beginning of next row.

2. Indexing of matrix elements

Indexing or subscripting a matrix is quite similar as referring to the elements of a vector, with the expansion of two dimensions in the matrix are rerferred to. Bracket symbol [ ] combined with colon, comma, and c() are often used in different cases to return the elements from an existing matrix.

In the following example, a matrix AMatrix is created first. Then the first and second column for all the rows of this matrix are returned. Of course, the returned elements can be assigned to another matrix if needed. Here the first comma denotes all the rows of this matrix.

> AMatrix = matrix(
+     c(6, 21, 33, 24, 52, 56, 67, 28, 91),
+     nrow = 3,            
+     ncol = 3,            
+     byrow = TRUE         
+ )
> cat("The new matrix is:\n")
The new matrix is:
> print(AMatrix)
     [,1] [,2] [,3]
[1,]    6   21   33
[2,]   24   52   56
[3,]   67   28   91
# Accessing first and second column, all rows
> print(AMatrix[, 1:2])
     [,1] [,2]
[1,]    6   21
[2,]   24   52
[3,]   67   28

Similarly, first and second rows , and first and third rows for all the columns of this matrix are returned in the following two examples.

#Accessing first and second rows, for all the columns
> print(AMatrix[1:2,])
     [,1] [,2] [,3]
[1,]    6   21   33
[2,]   24   52   56
> cat("Accessing first and second column\n")
Accessing first and third rows, for all the columnss
> print(AMatrix[c(1,3),])
     [,1] [,2] [,3]
[1,]    6   21   33
[2,]   67   28   91

3. Some basic functions for matrix

There are several basics function with the dimentions of matrix can be returned. In particular, dim() returns dimensions of each axis, nrow() returns row dimension, and ncol returns the column dimension. And length() returns how many elements in a matrix.

> cat("The Dimension of this AMatrix is :\n")
The Dimension of this AMatrix is :
> print(dim(AMatrix))
[1] 3 3
> cat("The Number of rows in this AMatrix is :\n")
The Number of rows in this AMatrix is :
> print(nrow(AMatrix))
[1] 3
> cat("Number of columns in this AMatrix is:\n")
Number of columns in this AMatrix is:
> print(ncol(AMatrix))
[1] 3
> cat("Number of all the elements in this AMatrix is:\n")
Number of all the elements in this AMatrix is:
> print(length(AMatrix))
[1] 9
> # OR
> print(prod(dim(AMatrix)))
[1] 9

You can also watch our video for matrix on our YouTube channel:

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago