# How to find the row that has maximum number of duplicates in an R matrix?

R ProgrammingServer Side ProgrammingProgramming

To find the row that has maximum number of duplicates in an R matrix, we can follow the below steps −

• First of all, create a matrix.
• Then, convert matrix into data.table then use order function with head function to find the row that has maximum number of duplicates.

## Create the matrix

Let’s create a matrix as shown below −

Live Demo

M<-matrix(rpois(40,1),ncol=2)
M

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

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

## Find the row that has maximum number of duplicates

Loading data.table package then converting matrix M into data.table object and finding the row that has maximum number of duplicates −

M<-matrix(rpois(40,1),ncol=2)
library(data.table)
DT<-data.table(M)
head(DT[,list(Duplicates=.N),by=names(DT)][order(Duplicates,decreasing=T)],1)

### Output

V1 V2 Duplicates
1: 1 0 5