How to remove duplicate columns from a matrix in R?


To remove duplicate columns from a matrix in R, we can use unique function.

For Example, if we have a matrix called M that contains some duplicate columns then we can use the below command to remove those duplicate columns −

unique(M,MARGIN=2)

Example 1

Following snippet creates a sample matrix −

M1<-matrix(c(rep(10,20),rpois(20,5),rep(10,20)),ncol=3,byrow=FALSE)
M1

The following matrix is created −

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

To remove duplicate column from matrix M1 on the above created matrix, add the following code to the above snippet −

M1<-matrix(c(rep(10,20),rpois(20,5),rep(10,20)),ncol=3,byrow=FALSE)
unique(M1,MARGIN=2)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

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

Example 2

Following snippet creates a sample matrix −

M2<-matrix(c(rpois(20,2),rep(1,20),rpois(20,5),rep(1,20)),ncol=4,byrow=FALSE)
M2

The following matrix is created −

  [,1] [,2] [,3] [,4]
[1,]  1  1    5   1
[2,]  4  1    8   1
[3,]  1  1    6   1
[4,]  1  1    2   1
[5,]  0  1    5   1
[6,]  2  1    5   1
[7,]  3  1    6   1
[8,]  1  1    4   1
[9,]  1  1    7   1
[10,] 0  1    5   1
[11,] 3  1    9   1
[12,] 1  1    2   1
[13,] 1  1    6   1
[14,] 0  1    3   1
[15,] 1  1    2   1
[16,] 0  1    4   1
[17,] 1  1    5   1
[18,] 4  1    3   1
[19,] 3  1    3   1
[20,] 4  1    3   1

To remove duplicate column from matrix M2 on the above created matrix, add the following code to the above snippet −

M2<-matrix(c(rpois(20,2),rep(1,20),rpois(20,5),rep(1,20)),ncol=4,byrow=FALSE)
unique(M2,MARGIN=2)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

   [,1] [,2] [,3]
[1,]  1  1    5
[2,]  4  1    8
[3,]  1  1    6
[4,]  1  1    2
[5,]  0  1    5
[6,]  2  1    5
[7,]  3  1    6
[8,]  1  1    4
[9,]  1  1    7
[10,] 0  1    5
[11,] 3  1    9
[12,] 1  1    2
[13,] 1  1    6
[14,] 0  1    3
[15,] 1  1    2
[16,] 0  1    4
[17,] 1  1    5
[18,] 4  1    3
[19,] 3  1    3
[20,] 4  1    3

Updated on: 03-Nov-2021

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements