# How to find the number of columns where all row values are equal in data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

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

• First of all, create a data.table object.

• 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 data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-sample(0:1,25,replace=TRUE)
y<-sample(0:1,25,replace=TRUE)
DT1<-data.table(x,y)
DT1

## Output

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

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

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 data.table object DT1 −

library(data.table)
x<-sample(0:1,25,replace=TRUE)
y<-sample(0:1,25,replace=TRUE)
DT1<-data.table(x,y)
sum(apply(DT1, 1, function(x) length(unique(x))==1))

## Output

 12


## Example 2

#### Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
v1<-rpois(25,1)
v2<-rpois(25,1)
DT2<-data.table(v1,v2)
DT2

## Output

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

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

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 data.table object DT2 −

library(data.table)
v1<-rpois(25,1)
v2<-rpois(25,1)
DT2<-data.table(v1,v2)
sum(apply(DT2, 1, function(x) length(unique(x))==1))

## Output

 7