## Matrices in R language

This article is about matrices in R language.

Matrix is a set of elements, sorted in rows and columns. Matrix of 2x3 size is a matrix with 2 rows and 3 columns.

## Example 1 - create matrix

You can use a *matrix* function to create matrix. The first argument is a number of items in matrix. In following arguments we have to declare the size of matrix - either by defining number of rows (*nrow* argument) or by defining of number of columns (*ncol* argument).

Lets create the matrix myMatrix with numbers from 1 to 20, sorted in 4 fows (or 5 columns). The sequence from 1 to 20 can be created by seq(1,20).

The command is:

1 |
> myMatrix = matrix(seq(1,20), nrow = 4) |

or:

1 |
> myMatrix = matrix(seq(1,20), ncol = 5) |

The results for both ways are identical.

1 2 3 4 5 6 |
> myMatrix [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 7 11 15 19 [4,] 4 8 12 16 20 |

The numbers are inserted by columns. To insert them by rows, use the *byrow* voluntary argument:

*byrow* = TRUE.

## Example 2 - matrix operations

With matrices, of course, we can perform all routine operations in R. If we add a number to the matrix or multiply it by a number, then this operation is applied to each element of the matrix individually. For example:

1 2 3 4 5 6 |
> myMatrix * 2 [,1] [,2] [,3] [,4] [,5] [1,] 2 10 18 26 34 [2,] 4 12 20 28 36 [3,] 6 14 22 30 38 [4,] 8 16 24 32 40 |

If we used *myMatix * myMatix*, then R would multiply the first element of myMatrix with the first, second with the other, etc. To perform a "real" multiplication of matrices, the operator should be bound by percentages. For example, to multiply myMatrix by a matrix transposed to myMatrix, just write:

1 2 3 4 5 6 |
> myMatrix %*% t(myMatrix) [,1] [,2] [,3] [,4] [1,] 565 610 655 700 [2,] 610 660 710 760 [3,] 655 710 765 820 [4,] 700 760 820 880 |

We see that transposition is performed by the function *t*. (Transposition of a matrix means switching of rows and columns (the first row of the matrix is the first column of the matrix to which it is transposed, etc.).)

## Example 3 - select item from matrix

We can select a row, column, or element from a matrix. To select the item from third row and second column use this command:

1 2 |
> myMatrix[3,2] [1] 7 |

Therefore, the index of an element is entered into square brackets, so that the first index is the row number and the second index is a column number.

To get the entire third line, just leave a blank space instead of the column index:

1 2 |
> myMatrix[3, ] [1] 3 7 11 15 19 |

Analogously - to get the second row, leave the row index empty.

1 2 |
> myMatrix[ ,2] [1] 5 6 7 8 |

Any item in matrix can be changed by defining a specific value. For example the item in third row and second column can be chaned to 1000 by this command:

1 2 3 4 5 6 7 |
< myMatrix[3,2] = 1000 < myMatrix [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 1000 11 15 19 [4,] 4 8 12 16 20 |