Remove Rows and Columns of a Matrix in R

In R, a matrix is a collection of elements of the same data type (boolean, numeric, or character) arranged into a fixed number of rows and columns.

matrix() function

Matrices can be created using the matrix() function. The matrix() function takes as input parameter a vector, followed by the nrow & ncol arguments to set the rows and columns of the formed matrix. Its return value is a 2d array, the matrix that was just formed.

Syntax

matrix(data, nrow, ncol)

Parameters

It takes the following argument values:

  • data: It is the 1d vector we want to reshape in the form of a matrix.
  • nrow: It is the number of rows of the matrix.
  • ncol: It is the number of columns of the matrix.

Return Value

A matrix has rows equal to nrows and columns equal to ncols.

Remove rows and columns of a matrix

There can be more than one way to remove rows or columns from a matrix. But, the simplest one is using the concatenation c() function.

In order to remove the desired rows or columns from the matrix, we’ll use the minus (-) sign followed by the c() function. Inside the c() function we will pass the row and column numbers that we want to remove.

Example: Reshaping matrix in R

Matrix <- matrix(c(0, 1, 2, 3, 4, 5, 6, 7, 8), nrow = 3, ncol =3)
print(Matrix)
 
Matrix <- Matrix[-c(1), -c(1)]
print("After Removal the Matrix is: ")
print(Matrix)
  • Line#1: Initializing a matrix having 3 rows & 3 columns.
  • Line#2:Printing the matrix that we initialized in line 1.
  • Line#4: Removing the first row and first column from the matrix using the c() function by passing the desired row and numbers.
  • Line#6: Printing the matrix after the removal of the first row and column.

Output

remove Rows and Columns of a Matrix in R
Remove Rows and Columns of a Matrix in R

Stay in the Loop

Get the daily email from Algoideas that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...