Matrix Construction R language

Rumman Ansari   Software Engineer   2023-03-24   5701 Share
☰ Table of Contents

Table of Content:


There are various ways to construct a matrix. When we construct a matrix directly with data elements, the matrix content is filled along the column orientation by default. For example, in the following code snippet, the content of is filled along the columns consecutively.

Program


B = matrix(c(2, 4, 3, 1, 5, 7), nrow = 3, ncol=2) 

Output

> B
     [,1] [,2]
[1,]    2    1
[2,]    4    5
[3,]    3    7
> 

Program


a <- matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE)

Output

> a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

Create Column name and Row names of a matrix

First check that column name and row names are exists or not by following command

> colnames(a)
NULL
> rownames(a)
NULL

Now we will assign column names and row names of the matrix

> colnames(a) <- c("a","b")

> rownames(a) <- c("c","d")

> colnames(a)
[1] "a" "b"

> rownames(a)
[1] "c" "d"

 

Transpose

We construct the transpose of a matrix by interchanging its columns and rows with the function .

> t(B)          # transpose of B 
     [,1] [,2] [,3] 
[1,]    2    4    3 
[2,]    1    5    7

 

Combining Matrices

The columns of two matrices having the same number of rows can be combined into a larger matrix. For example, suppose we have another matrix also with 3 rows.

> C = matrix( 
+   c(7, 4, 2), 
+   nrow=3, 
+   ncol=1) 
 
> C             # C has 3 rows 
     [,1] 
[1,]    7 
[2,]    4 
[3,]    2

Then we can combine the columns of and with cbind.

> cbind(B, C) 
     [,1] [,2] [,3] 
[1,]    2    1    7 
[2,]    4    5    4 
[3,]    3    7    2

Similarly, we can combine the rows of two matrices if they have the same number of columns with the rbind function.

> D = matrix( 
+   c(6, 2), 
+   nrow=1, 
+   ncol=2) 
 
> D             # D has 2 columns 
     [,1] [,2] 
[1,]    6    2 
 
> rbind(B, D) 
     [,1] [,2] 
[1,]    2    1 
[2,]    4    5 
[3,]    3    7 
[4,]    6    2

 

Deconstruction

We can deconstruct a matrix by applying the function, which combines all column vectors into one.

> c(B) 
[1] 2 4 3 1 5 7