How to find the number of unique values in each row of an R data frame?


To find the number of unique values in each row of an R data frame, we can use apply function with length and unique function. For example, if we have a data frame called df that contains multiple columns then the number of unique values in each row of df can be found by using the command apply(df,1,function(x) length(unique(x))).

Example1

Consider the below data frame −

Live Demo

> x1<-rpois(20,2)
> x2<-rpois(20,2)
> x3<-rpois(20,2)
> x4<-rpois(20,2)
> df1<-data.frame(x1,x2,x3,x4)
> df1

Output

   x1 x2 x3 x4 1   3  1  1  2 2   3  2  0  2 3   3  2  0  1 4   3  0  3  1 5   3  1  1  2 6   4  4  2  4 7   1  0  2  1 8   0  4  1  2 9   1  4  4  4 10  2  1  2  4 11  1  4  1  2 12  2  5  0  3 13  1  0  3  0 14  2  1  2  2 15  1  0  6  3 16  1  0  5  2 17  3  1  0  3 18  1  3  7  4 19  2  0  1  3 20  1  4  3  0

Finding the number of unique values in each row of df1 −

> apply(df1,1,function(x) length(unique(x)))
[1] 3 3 4 3 3 2 3 4 2 3 3 4 3 2 4 4 3 4 4 4

Example2

Live Demo

> y1<-rpois(20,1)
> y2<-rpois(20,1)
> y3<-rpois(20,1)
> y4<-rpois(20,1)
> y5<-rpois(20,1)
> df2<-data.frame(y1,y2,y3,y4,y5)
> df2

Output

   y1 y2 y3 y4 y5 1   2  0  0  0  1 2   0  1  0  1  3 3   1  1  1  1  1 4   4  1  1  1  0 5   3  0  0  0  0 6   0  0  0  1  1 7   0  0  3  0  0 8   1  2  3  1  1 9   1  1  3  0  1 10  2  1  1  1  1 11  0  2  0  2  1 12  2  0  1  0  1 13  0  2  0  0  1 14  0  0  1  3  0 15  1  1  2  1  0 16  1  2  2  2  1 17  0  0  0  1  1 18  0  2  0  0  1 19  1  1  0  1  2 20  2  2  0  2  2

Finding the number of unique values in each row of df2 −

> apply(df2,1,function(x) length(unique(x)))

Output

[1] 3 3 1 3 2 2 2 3 3 2 3 3 3 3 3 2 2 3 3 2

Updated on: 06-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements