How to remove multiple columns from matrix in R by using their names?


To remove multiple columns from matrix in R by using their names, we can follow the below steps −

  • First of all, create a matrix.

  • Then, add names to columns of the matrix.

  • After that, subset the matrix by deselecting the desired columns with negation and single square brackets for subsetting.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(100,5),ncol=4)
M

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     [,1] [,2] [,3] [,4]
[1,]  3    5    6    6
[2,]  4    1    3    5
[3,]  5    6    3    3
[4,]  4    6    8    6
[5,]  5    9    2    5
[6,]  1    6    7    5
[7,]  7    1    5    6
[8,]  5    6    4    6
[9,]  1    5   11    7
[10,] 3    3    6    4
[11,] 3    5    8    5
[12,] 1   10    3    1
[13,] 7   10    3    4
[14,] 5    6    4    5
[15,] 11   6   13    5
[16,] 8    4    6    1
[17,] 1    3    5    5
[18,] 2    7    7    7
[19,] 5    6    2    8
[20,] 6    4    6    7
[21,] 5    7    3   10
[22,] 4    5    1    2
[23,] 6    2    4    3
[24,] 4    5    4    4
[25,] 3   11    4    3

Add the column names

Using colnames function to add the column names to matrix M −

M<-matrix(rpois(100,5),ncol=4)
colnames(M)<-c("Grp1","Grp2","Grp3","Grp4")
M

Output

      Grp1 Grp2 Grp3 Grp4
[1,]  3    5    6    6
[2,]  4    1    3    5
[3,]  5    6    3    3
[4,]  4    6    8    6
[5,]  5    9    2    5
[6,]  1    6    7    5
[7,]  7    1    5    6
[8,]  5    6    4    6
[9,]  1    5   11    7
[10,] 3    3    6    4
[11,] 3    5    8    5
[12,] 1   10    3    1
[13,] 7   10    3    4
[14,] 5    6    4    5
[15,] 11   6   13    5
[16,] 8    4    6    1
[17,] 1    3    5    5
[18,] 2    7    7    7
[19,] 5    6    2    8
[20,] 6    4    6    7
[21,] 5    7    3   10
[22,] 4    5    1    2
[23,] 6    2    4    3
[24,] 4    5    4    4
[25,] 3   11    4    3

Updated on: 08-Nov-2021

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements