# How to check if an R matrix column contains only duplicate values?

To check if an R matrix column contains only duplicate values, we can use dim function for the dimension of the column after accessing the matrix column with table function. For example, if we have a matrix called M having five columns then we can check whether first column contains only duplicate values using the command dim(table(M[,1]))==1

## Example

Consider the below data frame −

Live Demo

M1<-matrix(c(rep(1,20),rep(2,20)),ncol=2)
M1

## Output

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

Checking whether columns in M1 contains duplicate values or not −

## Example

dim(table(M1[,1]))==1

[1] TRUE

## Example

dim(table(M1[,2]))==1

[1] TRUE

## Example

Live Demo

M2<-matrix(c(rep(1,20),rpois(20,2)),ncol=2)
M2

## Output

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

Checking whether columns in M2 contains duplicate values or not −

## Example

dim(table(M2[,1]))==1

[1] TRUE

## Example

dim(table(M2[,2]))==1

[1] FALSE

## Example

Live Demo

M3<-matrix(c(rep(5,20),rnorm(20,2,0.5)),ncol=2)
M3

## Output

[,1] [,2]
[1,]  5  1.3875392
[2,]  5  1.0927555
[3,]  5  2.2385030
[4,]  5  2.0015805
[5,]  5  2.0743614
[6,]  5  0.5072223
[7,]  5  2.1752948
[8,]  5  1.8959838
[9,]  5  2.0886671
[10,] 5  2.5035340
[11,] 5  1.5832031
[12,] 5  1.7593074
[13,] 5  1.7983010
[14,] 5  2.6664104
[15,] 5  1.2117921
[16,] 5  2.5033426
[17,] 5  1.8175419
[18,] 5  1.7202983
[19,] 5  2.1421497
[20,] 5  1.2270815

Checking whether columns in M3 contains duplicate values or not −

## Example

dim(table(M3[,1]))==1

[1] TRUE

## Example

dim(table(M3[,2]))==1

[1] FALSE