Matrix in R

In R we can create a matrix using the function called matrix(). We have to pass some arguments to the function which represents the set of elements in the vector. It takes arguments like the number of rows, columns, and entry of elements either in a row-wise fashion or column-wise.

The basic syntax of the matrix in R is

matrix(data, nrow, ncol, byrow = FALSE, dimnames = NULL)

  • data: it is the input data we want in the matrix.
  • nrow: defines the number of rows in matrix
  • ncol: defines the number of columns in matrix
  • byrow: A logical value indicating whether the matrix should be filled by rows (default is by columns).
  • dimnames: for providing names to the rows and columns.
R
# Create a 6x3 matrix with row and column names
mat <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9), 
              nrow = 6, ncol = 3, 
              dimnames = list(c("Row1", "Row2", "Row3", "Row4", "Row5", "Row6"), 
                              c("Col1", "Col2", "Col3")))
print(mat)

Output:

     Col1 Col2 Col3
Row1 1 7 4
Row2 2 8 5
Row3 3 9 6
Row4 4 1 7
Row5 5 2 8
Row6 6 3 9

Extract unique rows from a matrix using R

A matrix is a rectangular representation of elements that are put in rows and columns. The rows represent the horizontal data while the columns represent the vertical data in R Programming Language.

Similar Reads

Matrix in R

In R we can create a matrix using the function called matrix(). We have to pass some arguments to the function which represents the set of elements in the vector. It takes arguments like the number of rows, columns, and entry of elements either in a row-wise fashion or column-wise....

Extracting unique rows from a matrix using R

Method 1: Using unique() function...

Contact Us