How to identify duplicate values in a column of matrix in R?


We can easily identify duplicate values in a matrix by using duplicated function but it does not specify that the first occurrence is also duplicated. Therefore, we need to use it with OR sign | and the argument fromLast = TRUE of duplicated function so that the first occurrence of the duplicated values will be also identified as duplicate.

Example

 Live Demo

M1<-matrix(rpois(40,2),ncol=2)
M1

Output

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

Example

duplicated(M1[,1])|duplicated(M1[,1],fromLast=TRUE)

Output

[1] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE
[13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Example

 Live Demo

M2<-matrix(rpois(80,5),ncol=4)
M2

Output

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

Example

duplicated(M2[,2])|duplicated(M2[,2],fromLast=TRUE)

Output

[1] TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
[13] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE

Example

duplicated(M2[,3])|duplicated(M2[,3],fromLast=TRUE)

Output

[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[13] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE

Updated on: 07-Dec-2020

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements