In this tutorial, you will learn about matrix data type in R. We will discuss about how to create a matrix in R, how to access subset of a matrix and how to perform various operations like addition, multiplication, transpose, inverse, determinant and eigen values on matrix.

## Matrix in R

A matrix is a two-dimensional data structure in R. It is a set of elements appearing in rows and columns. Matrix in R is atomic (homogeneous) data structure. That is all the elements of the matrix must be of same mode (logical, numeric, complex or character).

A matrix can be created with the function matrix:

`matrix(data=NA, nrow=r, ncol=c, byrow=FALSE, dimnames=NULL)`

- By default matrices are created with their values running down successive column.
- It is also possible to specify that the matrix be filled by rows using
`byrow=TRUE`

. - The option dimnames allows to give names to the rows and columns.

### Attributes related to matrix (or data)

Some useful functions related to matrices in R are as follows:

Function | Description |
---|---|

`class(x)` |
Gives the class of object x as matrix |

`typeof(x)` |
Gives the type of data stored in matrix |

`dim(x)` |
Sets or changes the dimension of `x` |

`str(x)` |
Gives the structure of a matrix |

`nrow(x)` |
Gives the number of rows of a matrix |

`ncol(x)` |
Gives the number of columns of a matrix |

`rownames(x)` |
Gives row names of a matrix |

`colnames(x)` |
Gives column names of a matrix |

## How to Create matrix in R?

### Creating an empty matrix

An empty matrix can be created just by specifying the number of rows and number of columns of a matrix.

`AE <- matrix(nrow=3,ncol=4)`

Above command create an empty matrix (with elements `NA`

) of dimension 3 by 4 and store it in `AE`

.

`AE`

```
[,1] [,2] [,3] [,4]
[1,] NA NA NA NA
[2,] NA NA NA NA
[3,] NA NA NA NA
```

The `dim(x)`

function either display or set the dimension of object `x`

.

```
# display the dimension of given matrix
dim(AE)
```

`[1] 3 4`

The `nrow(x)`

and `ncol(x)`

display the number of rows and number of columns present in object `x`

.

```
# gives the number of rows in a given matrix
nrow(AE)
```

`[1] 3`

```
# gives the number of columns in a given matrix
ncol(AE)
```

`[1] 4`

The `class(x)`

function display the class of object `x`

. The object `AE`

is defined as a matrix, so the `class(AE)`

function display the class as `matrix`

.

`class(AE)`

`[1] "matrix" "array" `

In R, `NA`

are the logical constants of length 1. So the `typeof()`

an empty matrix shows `logical`

.

`typeof(AE) `

`[1] "logical"`

The `str(x)`

display the structure of object `x`

.

`str(AE)`

` logi [1:3, 1:4] NA NA NA NA NA NA ...`

The object `AE`

is a matrix, so the `str(AE)`

function display the structure of `AE`

with type as `logical`

, number of rows `1:3`

, number of columns `1:4`

and few elements of the object `AE`

.

### Creating Zero matrix

Zero matrix can be created by specifying the element 0 and the number of rows and columns of a matrix.

Below R command create a zero matrix with `3`

rows and `4`

columns.

```
A0 <- matrix(0, nrow = 3, ncol = 4)
A0
```

```
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
[3,] 0 0 0 0
```

```
# display the dimension of matrix
dim(A0)
```

`[1] 3 4`

```
# gives the number of rows of given matrix
nrow(A0)
```

`[1] 3`

`typeof(A0) `

`[1] "double"`

`str(A0)`

` num [1:3, 1:4] 0 0 0 0 0 0 0 0 0 0 ...`

### Creating a matrix from a sequence of numbers

Matrix in R can also be created using sequence of numbers using `:`

operator. By default, elements of sequence can be filled in a matrix column-wise.

Below R command create a matrix from sequence of numbers 1 to 9 with `3`

rows and `3`

columns.

```
B <- matrix(1:9, nrow = 3, ncol = 3)
B
```

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

Elements of sequence can also be filled in a matrix row-wise by specifying `byrow=T`

.

```
C <- matrix(1:9, nrow = 3, byrow = T)
C
```

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

Number of elements should be in multiples of number of rows or columns, otherwise R display warning message.

If the number of elements are not multiple of number of rows or number of columns, then R display warning message and create a matrix by recycling the elements.

`D <- matrix(1:9, nrow = 4)`

```
Warning in matrix(1:9, nrow = 4): data length [9] is not a sub-multiple or
multiple of the number of rows [4]
```

`D`

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

The first command create a matrix from the sequence of numbers `1:9`

with 4 rows and fill the elements column-wise and recycle the remaining elements form the start of the sequence.

### Creating a matrix from vector

Another way to create a matrix in R is to convert a vector into a matrix by specifying number of rows `nrow`

or number of column `ncol`

. By default the elements from the vector can be filled column-wise.

Suppose we have a vector `v1=c(1,2,3,4,5,6)`

. The second command create a matrix from vector `v1`

with number of rows equals `3`

and store the matrix in `A1`

.

```
v1 <- c(1, 2, 3, 4, 5, 6)
A1 <- matrix(v1, nrow = 3)
A1
```

```
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
```

```
# Display the structure
str(A1)
```

` num [1:3, 1:2] 1 2 3 4 5 6`

If we specify `byrow=T`

, then the matrix can be created from a vector `v1`

by filling the elements from the vector row-wise.

Below R code create a matrix `B1`

with number of rows `3`

from vector `v1`

but this time it fill the elements by row as we have used the option `byrow=T`

.

```
B1 <- matrix(v1, nrow = 3, byrow = T)
B1
```

```
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
```

```
# Display number of rows
nrow(B1)
```

`[1] 3`

```
# Display storage mode
typeof(B1)
```

`[1] "double"`

### Creating a Matrix from vector using a dimension attributes

A matrix in R can also be constructed from a vector by setting the dimension attribute of given vector. Assigning a dimension to a vector treats it as a matrix of specified dimension.

Below R code create a vector `da1`

.

```
# define a vector
da1 <- c(1, 2, 3, 4, 5, 6)
da1
```

`[1] 1 2 3 4 5 6`

`class(da1)`

`[1] "numeric"`

As `da1`

is a vector, the `class(da1)`

display the result as `numeric`

.

```
# set dimension of vector da1
# as 2 rows and 3 columns
dim(da1) <- c(2, 3)
da1
```

```
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
```

In the R code above, we have set the dimension of a vector `da1`

as `c(2,3)`

. R convert the vector `da1`

to a matrix of dimension 2 by 3. We can check this by using `class()`

function.

`class(da1)`

`[1] "matrix" "array" `

### Creating a matrix with dimension names

Rows and columns of a matrix can be labeled using `dimnames()`

command.

```
C1 <- matrix(c(52,56,81,46,143,143,37,34), nrow = 2,
dimnames = list(c("Female","Male"),
c("Black", "Blond","Brown","Red")))
C1
```

```
Black Blond Brown Red
Female 52 81 143 37
Male 56 46 143 34
```

```
# display dimension
dim(C1)
```

`[1] 2 4`

```
# Display dimension names
dimnames(C1)
```

```
[[1]]
[1] "Female" "Male"
[[2]]
[1] "Black" "Blond" "Brown" "Red"
```

Row names and column names of a matrix can also be assigned using `rownames()`

and `colnames()`

function.

Let us create a matrix `C2`

from sequence of numbers `11`

to `16`

with number of rows equals `2`

.

```
C2 <- matrix(11:16, nrow = 2)
C2
```

```
[,1] [,2] [,3]
[1,] 11 13 15
[2,] 12 14 16
```

Now assign the dimension names for `C2`

as follows:

```
rownames(C2) <- c("Row 1", "Row 2")
colnames(C2) <- c("Column 1", "Column 2", "Column 3")
dimnames(C2)
```

```
[[1]]
[1] "Row 1" "Row 2"
[[2]]
[1] "Column 1" "Column 2" "Column 3"
```

The first R code assign row names to matrix `C2`

and second R code assign column names to matrix `C2`

. The third R code display the dimension names of matrix `C2`

.

The row names and column names of matrix `C2`

can be retrieved using `rownames(C2)`

and `colnames(C2)`

command.

`rownames(C2)`

`[1] "Row 1" "Row 2"`

`colnames(C2)`

`[1] "Column 1" "Column 2" "Column 3"`

### Creating a matrix using `cbind()`

and `rbind()`

function

Matrices in R can also be created using `cbind()`

(column-binding) or `rbind()`

(row-binding) functions.

```
# combine columns
C3 <- cbind(c(1, 2), c(3, 4))
C3
```

```
[,1] [,2]
[1,] 1 3
[2,] 2 4
```

```
# combine rows
C4 <- rbind(c(10, 13), c(23, 34))
C4
```

```
[,1] [,2]
[1,] 10 13
[2,] 23 34
```

`cbind()`

and `rbind()`

can also be use to combine two or more matrices.

```
# combine two matrices using cbind
C5 <- cbind(C3, C4)
C5
```

```
[,1] [,2] [,3] [,4]
[1,] 1 3 10 13
[2,] 2 4 23 34
```

To combine two or more matrices using `cbind()`

function, the number of rows must be same in all the matrices.

```
# combine two matrices using rbind
C6 <- rbind(C3, C4)
C6
```

```
[,1] [,2]
[1,] 1 3
[2,] 2 4
[3,] 10 13
[4,] 23 34
```

To combine two or more matrices using `rbind()`

function, the number of columns must be same in all the matrices.

## Accessing matrix elements in R

### Accessing Rows/Columns using index

Elements of a matrix can be accessed by specifying row number(s) and/or column number(s). Like

`mat1[i,]`

returns $i^{th}$ row,`mat[,j]`

returns $j^{th}$ column and`mat1[i,j]`

returns $(i,j)^{th}$ element of matrix.

Let us create a matrix `mat1`

from sequence of numbers from `1`

to `9`

with `3`

rows and elements are filled by row.

```
mat1 <- matrix(1:9, nrow = 3, byrow = TRUE)
mat1
```

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

Below R code returns only first row of matrix `mat1`

.

```
# returns 1st row of matrix mat1
mat1[1, ]
```

`[1] 1 2 3`

Below R code returns only third column of matrix `mat1`

.

```
# returns 3rd column of matrix mat1
mat1[, 3]
```

`[1] 3 6 9`

Above R code returns third column of matrix `mat1`

but it return a vector, even though the object is a matrix. To prevent this from happening we use `drop=FALSE`

argument as follows:

```
# returns 3rd column of matrix mat1
mat1[, 3, drop = FALSE]
```

```
[,1]
[1,] 3
[2,] 6
[3,] 9
```

Below R code return the element from second row and third column of matrix `mat1`

.

```
# returns value from mat1 in the
# 2nd row and 3rd column
mat1[2, 3]
```

`[1] 6`

Below R code returns the first and second row and third column of matrix `mat1`

.

```
# returns the elements from mat1
# in the first 2 rows ad 3rd column
mat1[1:2, 3]
```

`[1] 3 6`

To extract non-adjacent rows or columns, use `c()`

(combine) function.

Below R code returns first and third row of matrix `mat1`

.

```
# returns the elements from mat1
# in the first and third row
mat1[c(1, 3), ]
```

```
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
```

The same can also be achieved by negative indexing. Below R code display all the rows except second row of matrix `mat1`

.

```
# returns the elements from all
# rows except 2nd row
mat1[-2, ]
```

```
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
```

### Accessing by Row/Column names

Recall the matrix `C1`

defined above.

`C1`

```
Black Blond Brown Red
Female 52 81 143 37
Male 56 46 143 34
```

Below R code return the elements of row with row name `Male`

from matrix `C1`

.

`C1["Male", ]`

```
Black Blond Brown Red
56 46 143 34
```

Below R code return the elements of column with column name `Non-smoker`

from matrix `C1`

.

`C1[, "Blond"]`

```
Female Male
81 46
```

We can combine index and the row or column name to extract the data from given matrix.

Below R code return the elements from first row and the columns with column names `Blond`

and `Red`

.

`C1[1, c("Blond", "Red")]`

```
Blond Red
81 37
```

## Matrix Operations in R

- Arithmetic operations on matrices are element-wise: +, -, *,/
- Matrix multiplication:
`%*%`

- Transpose of a matrix :
`t()`

- To solve the system of linear equations
`Ax = b`

:`solve(A,b)`

- To find the inverse of a matrix $A^{-1}$ :
`solve(A)`

- To computes eigen values and eigen vectors:
`eigen()`

- To compute determinant of a matrix:
`det(A)`

### Multiplication by scalar

`A <- matrix(c(1, 2, 3, 4), nrow = 2)`

Below R code multiply every element of `A`

by 3.

`A * 3`

```
[,1] [,2]
[1,] 3 9
[2,] 6 12
```

### Addition/subtraction of matrices

Addition and subtraction of matrices in R is performed element-wise.

```
B <- matrix(c(4, 5, 5, 3), nrow = 2)
# Addition of two matrices A and B
A + B
```

```
[,1] [,2]
[1,] 5 8
[2,] 7 7
```

Element-wise addition is performed on two matrices `A`

and `B`

.

```
# Difference of matrix B from A
A - B
```

```
[,1] [,2]
[1,] -3 -2
[2,] -3 1
```

### Matrix multiplication

`A*A`

gives a new matrix with element-wise multiplication, where as `A%*% A`

gives actual matrix multiplication.

`A`

```
[,1] [,2]
[1,] 1 3
[2,] 2 4
```

Using `*`

operator, the code `A*A`

returns a new matrix with element-wise multiplication.

```
# Element-wise multiplication
A * A
```

```
[,1] [,2]
[1,] 1 9
[2,] 4 16
```

The actual matrix multiplication can be obtained using `%*%`

operator.

```
# Matrix Multiplication
A %*% A
```

```
[,1] [,2]
[1,] 7 15
[2,] 10 22
```

The operator `*`

perform element-wise matrix multiplication whereas the operator `%*%`

perform actual matrix multiplication.

### Transpose of a matrix

The function `t(x)`

returns the transpose of object `x`

, where object `x`

may be a matrix or data frame.

First R Code display matrix `A`

and second R code compute the transpose of matrix `A`

.

`A`

```
[,1] [,2]
[1,] 1 3
[2,] 2 4
```

```
# transpose of a matrix A
t(A)
```

```
[,1] [,2]
[1,] 1 2
[2,] 3 4
```

### Inverse of a matrix

The arithmetic operations on matrices are element-wise. Hence if we use `A^(-1)`

, R will calculate a new matrix as a reciprocal of each element of matrix A.

```
# Matrix of reciprocal of each elements
A ^ (-1)
```

```
[,1] [,2]
[1,] 1.0 0.3333333
[2,] 0.5 0.2500000
```

Above R code returns a matrix as a reciprocal of each element of matrix A.

Inverse of a square matrix in R can be computed using `solve()`

function.

```
# Inverse of a matrix A
solve(A)
```

```
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
```

### Determinant of a matrix

The `det(x)`

function returns the determinant of matrix `x`

.

```
# determinant of Matrix A
det(A)
```

`[1] -2`

### Eigen values and eigen vectors of a matrix

The function `eigen(x)`

computes the eigenvalues and eigen-vectors of matrix `x`

.

```
# eigen values and eigen vectors of A
eigen(A)
```

```
eigen() decomposition
$values
[1] 5.3722813 -0.3722813
$vectors
[,1] [,2]
[1,] -0.5657675 -0.9093767
[2,] -0.8245648 0.4159736
```

Only eigen values can be extracted using following R code:

```
# gives only eigen values of A
eigen(A)$values
```

`[1] 5.3722813 -0.3722813`

Only eigen vectors can be extracted using following R code:

```
# gives only eigen vectors of A
eigen(A)$vectors
```

```
[,1] [,2]
[1,] -0.5657675 -0.9093767
[2,] -0.8245648 0.4159736
```

## Addition functions for matrices in R

Some additional functions on matrices in R are as follows:

Function | Explanation |
---|---|

`diag()` |
Create diagonal matrix or return diagonal |

`rowSums()` |
Sum of elements of rows |

`colSums()` |
Sum of elements of columns |

`rowMeans()` |
Mean of elements of rows |

`colMeans()` |
Mean of elements of columns |

### diag() Function

The `diag()`

function is very useful function for matrices. If the argument of a `diag()`

function is a vector, it creates a diagonal matrix with the principal diagonal as elements of vector.

```
## Create a vector
a <- c(1, 3, 7)
a
```

`[1] 1 3 7`

```
A <- diag(a)
A
```

```
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 3 0
[3,] 0 0 7
```

If the argument of a `diag()`

function is a matrix, it will display the principal diagonal elements.

```
B <- matrix(1:9, nrow = 3)
B
```

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

```
## returns principal diagonal of B
diag(B)
```

`[1] 1 5 9`

If the argument of `diag()`

function is a scalar, (say `diag(m)`

) it returns identity matrix of order $m\times m$.

Below R code, returns a identity matrix of order $3\times 3$.

`diag(3)`

```
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
```

### rowSums() and rowMeans() function on Matrix

The sum and means for each row of a matrix can be computed using `rowSums()`

and `rowMeans()`

functions respectively.

```
# compute the sum for each row of B
rowSums(B)
```

`[1] 12 15 18`

```
# compute the means for each row of B
rowMeans(B)
```

`[1] 4 5 6`

### colSums() and colMeans() function on Matrix

The sum and means for each column of a matrix can be computed using `colSums()`

and `colMeans()`

functions respectively. Check apply() function in R for more functions.

```
# compute the sum for each column of B
colSums(B)
```

`[1] 6 15 24`

```
# compute the mean for each column of B
colMeans(B)
```

`[1] 2 5 8`

Note that to compute rowSums, colSums, rowMeans, colMeans and other functions, we can use apply() function in R.

## Endnote

In this tutorial you learned about what is `matrix`

data structure in R, how to create `matrix`

, how to access subset of matrix in R and how to perform various operations on matrices in R with some illustrations.

To learn more about other data structures in R, please refer to the following tutorials:

- Data Types in R
- Data Structures in R
- Variables and Constants in R
- Vectors in R
- Array in R
- List in R
- Factors in R
- Data Frames in R

Hopefully you enjoyed learning this tutorial on `matrix`

type data structure in R. Hope the content is more than sufficient to understand `matrix`

in R.