How to find the number of columns where all row values are equal in R matrix?

R ProgrammingServer Side ProgrammingProgramming

To find the number of columns where all row values are equal in R matrix, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use sum function along with length and apply function to find the number of columns where all row values are equal.

Example 1

Create the matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(50,5),ncol=2)
M1

Output

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

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

Find the number of columns where all row values are equal

Using sum function along with length and apply function to find the number of columns where all row values are equal in matrix M1 −

M1<-matrix(rpois(50,5),ncol=2)
sum(apply(M1, 1, function(x) length(unique(x))==1))

Output

[1] 7

Example 2

Create the matrix

Let’s create a matrix as shown below −

M2<-matrix(sample(1:5,50,replace=TRUE),ncol=2)
M2

Output

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

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

Find the number of columns where all row values are equal

Using sum function along with length and apply function to find the number of columns where all row values are equal in matrix M2 −

M2<-matrix(sample(1:5,50,replace=TRUE),ncol=2)
sum(apply(M2, 1, function(x) length(unique(x))==1))

Output

[1] 6
raja
Published on 10-Nov-2021 06:49:23
Advertisements