An R Introduction to Statistics

Matrix Construction

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 B is filled along the columns consecutively.

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

Transpose

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

> 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 C 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 B and C 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 c function, which combines all column vectors into one.

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