Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of rows where all columns have identical values

Tags:

r

I have a dataframe and I want to count the number of rows which have the same value for all the columns, within each row.

For example, I have this data:

cmp <- read.table(text = "
A B C D
1 1 1 0
1 1 1 1
2 2 2 2
3 3 3 0", header = TRUE)

Here, the count is 2, because the second row and third row have only one unique value each, only 1s, and only 2s, respectively.

Thanks in advance.

like image 705
Siddharth Thanga Mariappan Avatar asked Dec 04 '22 21:12

Siddharth Thanga Mariappan


1 Answers

This, which uses apply() to count the number of distinct elements in each row, should do the trick:

sum(apply(cmp, 1, function(x) length(unique(x))==1))
## [1] 2
like image 62
Josh O'Brien Avatar answered Dec 06 '22 10:12

Josh O'Brien