Content is user-generated and unverified.

    Matrices in R

    What is a Matrix?

    A matrix is a two-dimensional array of data arranged in rows and columns, where all elements must be of the same data type (all numbers, all text, or all logical values). Think of it as a rectangular table of data, similar to a simple spreadsheet but more structured.

    Key characteristics:

    • Two-dimensional (has both rows and columns)
    • All elements must be the same data type (homogeneous)
    • Elements are arranged in a rectangular grid
    • Each element can be accessed by its row and column position

    Creating Matrices

    Using the matrix() function:

    r
    # Create a 3x4 matrix from a vector
    data_vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
    my_matrix <- matrix(data_vector, nrow = 3, ncol = 4)
    my_matrix
         [,1] [,2] [,3] [,4]
    [1,]    1    4    7   10
    [2,]    2    5    8   11
    [3,]    3    6    9   12
    
    # Fill by rows instead of columns
    my_matrix_byrow <- matrix(data_vector, nrow = 3, ncol = 4, byrow = TRUE)
    my_matrix_byrow
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3    4
    [2,]    5    6    7    8
    [3,]    9   10   11   12

    Specifying only rows OR columns:

    r
    # Specify only number of rows (columns calculated automatically)
    matrix(1:12, nrow = 4)
         [,1] [,2] [,3]
    [1,]    1    5    9
    [2,]    2    6   10
    [3,]    3    7   11
    [4,]    4    8   12
    
    # Specify only number of columns (rows calculated automatically)
    matrix(1:12, ncol = 3)
         [,1] [,2] [,3]
    [1,]    1    5    9
    [2,]    2    6   10
    [3,]    3    7   11
    [4,]    4    8   12

    Creating special matrices:

    r
    # Matrix of zeros
    zero_matrix <- matrix(0, nrow = 2, ncol = 3)
    zero_matrix
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    # Matrix of ones
    ones_matrix <- matrix(1, nrow = 3, ncol = 2)
    ones_matrix
         [,1] [,2]
    [1,]    1    1
    [2,]    1    1
    [3,]    1    1
    
    # Identity matrix (diagonal of 1s, rest 0s)
    identity_matrix <- diag(3)  # 3x3 identity matrix
    identity_matrix
         [,1] [,2] [,3]
    [1,]    1    0    0
    [2,]    0    1    0
    [3,]    0    0    1

    Combining vectors to create matrices:

    r
    # Row binding - stack vectors as rows
    vector1 <- c(1, 2, 3)
    vector2 <- c(4, 5, 6)
    vector3 <- c(7, 8, 9)
    
    row_matrix <- rbind(vector1, vector2, vector3)
    row_matrix
            [,1] [,2] [,3]
    vector1    1    2    3
    vector2    4    5    6
    vector3    7    8    9
    
    # Column binding - place vectors side by side as columns
    col_matrix <- cbind(vector1, vector2, vector3)
    col_matrix
         vector1 vector2 vector3
    [1,]       1       4       7
    [2,]       2       5       8
    [3,]       3       6       9

    Understanding Matrix Structure

    Checking matrix properties:

    r
    my_matrix <- matrix(1:12, nrow = 3, ncol = 4)
    
    # Check if it's a matrix
    is.matrix(my_matrix)
    [1] TRUE
    
    # Get dimensions
    dim(my_matrix)        # rows, columns
    [1] 3 4
    
    nrow(my_matrix)       # number of rows
    [1] 3
    
    ncol(my_matrix)       # number of columns  
    [1] 4
    
    # Check data type
    class(my_matrix)
    [1] "matrix" "array"
    
    typeof(my_matrix)     # underlying data type
    [1] "integer"
    
    # Get structure overview
    str(my_matrix)
     int [1:3, 1:4] 1 2 3 4 5 6 7 8 9 10 ...

    Accessing Matrix Elements (Indexing)

    Individual elements:

    r
    my_matrix <- matrix(1:12, nrow = 3, ncol = 4)
    
    # Access element in row 2, column 3
    my_matrix[2, 3]
    [1] 8
    
    # Access element in row 1, column 1
    my_matrix[1, 1]
    [1] 1

    Entire rows or columns:

    r
    # Get entire row 2 (leave column position empty)
    my_matrix[2, ]
    [1] 2 5 8 11
    
    # Get entire column 3 (leave row position empty)
    my_matrix[, 3]
    [1] 7 8 9
    
    # Get multiple rows
    my_matrix[c(1, 3), ]
         [,1] [,2] [,3] [,4]
    [1,]    1    4    7   10
    [2,]    3    6    9   12
    
    # Get multiple columns
    my_matrix[, c(2, 4)]
         [,2] [,4]
    [1,]    4   10
    [2,]    5   11
    [3,]    6   12

    Submatrices (rectangular sections):

    r
    # Get rows 1-2, columns 2-3
    my_matrix[1:2, 2:3]
         [,1] [,2]
    [1,]    4    7
    [2,]    5    8
    
    # Get specific rows and columns
    my_matrix[c(1, 3), c(1, 4)]
         [,1] [,2]
    [1,]    1   10
    [2,]    3   12

    Adding Names to Matrices

    Row and column names:

    r
    my_matrix <- matrix(1:12, nrow = 3, ncol = 4)
    
    # Add row names
    rownames(my_matrix) <- c("Row1", "Row2", "Row3")
    
    # Add column names
    colnames(my_matrix) <- c("Col1", "Col2", "Col3", "Col4")
    
    my_matrix
         Col1 Col2 Col3 Col4
    Row1    1    4    7   10
    Row2    2    5    8   11
    Row3    3    6    9   12
    
    # Access by name
    my_matrix["Row2", "Col3"]
    [1] 8
    
    my_matrix["Row1", ]
    Col1 Col2 Col3 Col4 
       1    4    7   10

    Setting names during creation:

    r
    named_matrix <- matrix(1:6, nrow = 2, ncol = 3,
                          dimnames = list(c("X", "Y"), 
                                        c("A", "B", "C")))
    named_matrix
      A B C
    X 1 3 5
    Y 2 4 6

    Modifying Matrices

    Changing individual elements:

    r
    my_matrix <- matrix(1:12, nrow = 3, ncol = 4)
    
    # Change single element
    my_matrix[2, 3] <- 99
    my_matrix
         [,1] [,2] [,3] [,4]
    [1,]    1    4    7   10
    [2,]    2    5   99   11
    [3,]    3    6    9   12
    
    # Change entire row
    my_matrix[1, ] <- c(100, 200, 300, 400)
    my_matrix
         [,1] [,2] [,3] [,4]
    [1,]  100  200  300  400
    [2,]    2    5   99   11
    [3,]    3    6    9   12
    
    # Change entire column
    my_matrix[, 2] <- c(50, 60, 70)
    my_matrix
         [,1] [,2] [,3] [,4]
    [1,]  100   50  300  400
    [2,]    2   60   99   11
    [3,]    3   70    9   12

    Adding rows or columns:

    r
    original_matrix <- matrix(1:6, nrow = 2, ncol = 3)
    
    # Add a row
    new_row <- c(7, 8, 9)
    expanded_matrix <- rbind(original_matrix, new_row)
    expanded_matrix
        [,1] [,2] [,3]
           1    3    5
           2    4    6
    new_row  7    8    9
    
    # Add a column
    new_col <- c(10, 20, 30)
    expanded_matrix <- cbind(expanded_matrix, new_col)
    expanded_matrix
        [,1] [,2] [,3] new_col
           1    3    5      10
           2    4    6      20
    new_row  7    8    9      30

    Matrix Arithmetic

    Element-wise operations:

    r
    matrix1 <- matrix(1:6, nrow = 2, ncol = 3)
    matrix2 <- matrix(7:12, nrow = 2, ncol = 3)
    
    matrix1
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    
    matrix2
         [,1] [,2] [,3]
    [1,]    7    9   11
    [2,]    8   10   12
    
    # Addition
    matrix1 + matrix2
         [,1] [,2] [,3]
    [1,]    8   12   16
    [2,]   10   14   18
    
    # Multiplication (element-wise)
    matrix1 * matrix2
         [,1] [,2] [,3]
    [1,]    7   27   55
    [2,]   16   40   72
    
    # Operations with single values
    matrix1 + 10
         [,1] [,2] [,3]
    [1,]   11   13   15
    [2,]   12   14   16
    
    matrix1 * 3
         [,1] [,2] [,3]
    [1,]    3    9   15
    [2,]    6   12   18

    Matrix multiplication (mathematical):

    r
    # True matrix multiplication using %*%
    A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
    B <- matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2)
    
    A
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    
    B
         [,1] [,2]
    [1,]    5    7
    [2,]    6    8
    
    # Matrix multiplication
    A %*% B
         [,1] [,2]
    [1,]   23   31
    [2,]   34   46

    Transpose:

    r
    original <- matrix(1:6, nrow = 2, ncol = 3)
    original
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    
    # Transpose (flip rows and columns)
    t(original)
         [,1] [,2]
    [1,]    1    2
    [2,]    3    4
    [3,]    5    6

    Useful Matrix Functions

    r
    my_matrix <- matrix(c(1, 4, 2, 5, 3, 6), nrow = 2, ncol = 3)
    
    # Apply functions to rows or columns
    rowSums(my_matrix)    # Sum of each row
    [1] 6 15
    
    colSums(my_matrix)    # Sum of each column
    [1] 5 7 9
    
    rowMeans(my_matrix)   # Mean of each row
    [1] 2.0 5.0
    
    colMeans(my_matrix)   # Mean of each column
    [1] 2.5 3.5 4.5
    
    # Apply custom functions
    apply(my_matrix, 1, max)  # Maximum of each row (1 = rows)
    [1] 3 6
    
    apply(my_matrix, 2, min)  # Minimum of each column (2 = columns)
    [1] 1 4 2

    Working with Missing Values

    r
    matrix_with_na <- matrix(c(1, 2, NA, 4, 5, 6), nrow = 2, ncol = 3)
    matrix_with_na
         [,1] [,2] [,3]
    [1,]    1   NA    5
    [2,]    2    4    6
    
    # Check for missing values
    is.na(matrix_with_na)
         [,1]  [,2]  [,3]
    [1,] FALSE  TRUE FALSE
    [2,] FALSE FALSE FALSE
    
    # Functions that handle NA values
    rowSums(matrix_with_na, na.rm = TRUE)  # Remove NAs before summing
    [1] 6 12
    
    colMeans(matrix_with_na, na.rm = TRUE)
    [1] 1.5 4.0 5.5

    Converting Between Data Types

    Matrix to vector:

    r
    my_matrix <- matrix(1:6, nrow = 2, ncol = 3)
    
    # Convert to vector (column-wise by default)
    as.vector(my_matrix)
    [1] 1 2 3 4 5 6
    
    # Convert to vector row-wise
    as.vector(t(my_matrix))
    [1] 1 3 5 2 4 6

    Matrix to data frame:

    r
    # Convert matrix to data frame (more flexible for mixed data types)
    my_df <- as.data.frame(my_matrix)
    my_df
      V1 V2 V3
    1  1  3  5
    2  2  4  6
    
    class(my_df)
    [1] "data.frame"

    Key Points to Remember

    1. Matrices are homogeneous - all elements must be the same data type
    2. Two-dimensional indexing - use [row, column] notation
    3. Column-major order - R fills matrices by columns by default (use byrow = TRUE to fill by rows)
    4. Element-wise vs. matrix operations - * is element-wise, %*% is matrix multiplication
    5. Leave positions empty - use [2, ] for entire row 2, [, 3] for entire column 3
    6. Names are helpful - use rownames() and colnames() for better readability
    7. apply() function - powerful for applying functions across rows or columns
    8. Matrices vs. data frames - matrices for homogeneous numerical data, data frames for mixed types

    Understanding matrices is important for mathematical computations, image processing, and as stepping stones to understanding more complex data structures in R.

    Content is user-generated and unverified.