R Matrices

  • A matrix is a two dimensional collection of elements of the same data type
  • Matrices have columns and rows.
  • Matrices are created using the matrix() function


  • data: a vector of data to fill the matrix.
  • nrow: the number of rows in the matrix.
  • ncol: the number of columns in the matrix.
  • byrow: a logical value specifying whether the matrix should be filled by rows (byrow = TRUE) or by columns (byrow = FALSE).
  • dimnames: a list with two components, giving the row and column names.

Example 1

Example 2

Access Matrix Items

  • Matrix Items may be accessed based on their index positions. Such as matrix_items[1, 2]. This means that the item located at row #1 and column #2 is being accessed
  • An entire row may be accessed. For example in matrix_items[1, ] (all of row number 1 is being accessed)

Example 1:

Access More Than One Row

Access More Than One Column

Add Rows and Columns

  • Use the cbind() function to add additional columns in a Matrix.
  • Syntax– cbind(vector 1, vector2, vector3…)

Remove Third column of a Matrix using c()

Check if an Item Exists in a Matrix

To check if a string exists in a matrix use the string %in% variable search

Find the Dimension of a Matrix using dim()

Find the Length (number of elements) of a Matrix using length()

Loop Through a Matrix

Combine Two Matrices

To combine matrices in R, the cbind() or the rbind() may be used

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top