How to remove rows and columns of a matrix in R

Overview

To understand what a matrix is and how to create a matrix in R, read this shot.

Removing rows and columns from an existing matrix

To remove the row(s) and column(s) of a current matrix in R, we use the c() function.

Parameters of the c() function

The numbers that represent the row number and column number we wish to remove are the parameters. For example:

[-c(1), -c(1)]

The code above specifies the first row and the first column.

Code example

mymatrix <- matrix(c("apple", "banana", "cherry", "orange", "mango", "pineapple"), nrow = 3, ncol =2)
# removing the first row an first colummn of the matrix
mymatrix <- mymatrix[-c(1), -c(1)]
mymatrix
Using the c() function

Code explanation

  • Line 2: We create a 3x2 matrix (a matrix with 3 rows and 2 columns) called mymatrix. We use the matrix() function and pass the parameter values of its shape. nrow = 3 represents 3 rows, while ncol = 2 represents 2 columns.
  • Line 4: Using the c() function, we remove the first row and first column [-c(1), -c(1)] from the matrix.
  • Line 6: We print the modified matrix.

Free Resources