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 1
s, and only 2
s, respectively.
Thanks in advance.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With