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:

or:

The results for both ways are identical.

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:

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:

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:

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:

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

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:

Leave a Reply

Your email address will not be published.

*

clear formPost comment