36  Matrix

Tableau matematika!

A matrix is a programming implementation of a mathematical matrix Chapter 5. It is a rectangular object where each element is identified by its row and column position.

Reusing the analogy of a vector as a stacked apartment building Chapter 35, a matrix allows multiple apartments on each floor. An apartment is then identified by its floor number and its position on that floor. Similar to a vector, a matrix must be homogeneous. A matrix can therefore be described by its data type, such as an integer matrix or a numeric matrix.

In data science, datasets are often heterogeneous, in which case a data frame Chapter 38 or a list Chapter 39 is used. In general, a matrix object is best suited for mathematical computation.

Formal

To construct a matrix in R, the syntax matrix() is used.

matrix_name <- matrix(data, nrow = n_rows, ncol = n_cols)

The data argument takes a vector of length n_rows * n_cols so that each value is assigned to all the entry of the matrix. By default, R fills matrices column-by-column.

  • The dimensions of a matrix represent the number of rows and columns it contains and can be retrieved with dim(). Alternatively, nrow() and ncol() return the row and column counts individually.

  • To access an element in a matrix, square brackets with a comma [row, column] are used: matrix_name[2, 3] returns the entry at the second row and third column. The positional indices must be integers.

  • In R, negative indices exclude specific rows or columns. For example, matrix_name[-2, ] excludes the second row, while matrix_name[, -3] excludes the third column from the output.

Examples

Constructing the matrix used in Chapter 5.

mat <-
    matrix(c(6, 3, 0, 1, 3, 1, 10, 0, 0.5, 0, 0, 2),
    nrow = 4,
    ncol = 3)
mat
     [,1] [,2] [,3]
[1,]    6    3  0.5
[2,]    3    1  0.0
[3,]    0   10  0.0
[4,]    1    0  2.0

Notice that numerical values are automatically formatted in the console output. When a matrix or vector contains at least one decimal number, R displays all numeric values in that structure with consistent decimal formatting (e.g., 6.0 or 3.0) to preserve alignment across rows and columns.

# Access the entire first row by specifying row index 1 and leaving the column index blank
mat[1, ]
[1] 6.0 3.0 0.5
# Access the entire first column by specifying column index 1 and leaving the row index blank
mat[, 1]
[1] 6 3 0 1
# Access the entry at row 3, column 2
mat[3, 2]
[1] 10
# Access elements in columns 1 and 2 of the first row
mat[1, c(1, 2)]
[1] 6 3
# Access rows 2 and 4 across all columns
mat[c(2, 4), ]
     [,1] [,2] [,3]
[1,]    3    1    0
[2,]    1    0    2
# Access columns 1 and 3 across all rows
mat[, c(1, 3)]
     [,1] [,2]
[1,]    6  0.5
[2,]    3  0.0
[3,]    0  0.0
[4,]    1  2.0

Tips and warnings

  • The indexing [row_index, column_index] follows the \(a_{i,j}\) notation used in mathematics to denote the entry at row \(i\) and column \(j\) Chapter 5. Leaving one of the dimension blank means seleection all values along that dimension.

  • A matrix is typically used for mathematical operations Chapter 6 and Chapter 7.

  • Notice that there is no separate chapter on vectors in basic mathematics. This is because, mathematically, a vector is a matrix where either the number of rows or the number of columns is equal to one.

  • All elements in a matrix must be of the same data type. If different data types are combined, R automatically converts—or coerces—the entire matrix according to a strict hierarchy: Logical < Integer < Numeric < Character. Values lower in this hierarchy are converted to the higher type across all entries. See examples of coercion in Chapter 35.

  • Column and row names can also be assigned to a matrix. However, this is not the most common use of a matrix; a data frame Chapter 38 is more commonly used for named tabular data.

    # Assign names to rows
    rownames(mat) <- c("Rabe", "Rakoto", "Sanda", "Dora")
    
    # Assign names to columns
    colnames(mat) <- c("Banana", "Strawberries", "Voatsinefy")
    
    # Display matrix with dimnames
    mat
           Banana Strawberries Voatsinefy
    Rabe        6            3        0.5
    Rakoto      3            1        0.0
    Sanda       0           10        0.0
    Dora        1            0        2.0