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


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

  • First of all, create a data frame.

  • 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 frame

Let’s create a data frame as shown below −

x<-rpois(25,1)
y<-rpois(25,1)
z<-rpois(25,1)
df<-data.frame(x,y,z)
df

Output

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

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

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 frame df1 −

x<-rpois(25,1)
y<-rpois(25,1)
z<-rpois(25,1)
df<-data.frame(x,y,z)
sum(apply(df, 1, function(x) length(unique(x))==1))

Output

[1] 5

Example 2

Create the data frame

Let’s create a data frame as shown below −

v1<-round(rnorm(25),0)
v2<-round(rnorm(25),0)
dat<-data.frame(v1,v2)
dat

Output

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

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

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 frame df2 −

v1<-round(rnorm(25),0)
v2<-round(rnorm(25),0)
dat<-data.frame(v1,v2)
sum(apply(dat, 1, function(x) length(unique(x))==1))

Output

[1] 6

Updated on: 16-Nov-2021

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements