meles
meles

Reputation: 456

Countif with multiple criterias in R

I would like to count all rows where two criterias are matched. My approach was:

a <- c(2,1,2,2,3,4,2,1,9)
b <- c(2,1,2,1,4,4,5,6,7)
c <- data.frame(a,b)
sum((c['a']==2) && (c['b']==2))

but for some reason this gives 1 instead of two. How could I count rows if multiple criterias are matched?

Upvotes: 3

Views: 11929

Answers (2)

Stuart
Stuart

Reputation: 1492

I think you are using the wrong ampersand operator. Try this:

sum(c['a']==2 & c['b']==2)
[1] 2

If you might have NAs in column a or b you might also try:

length(intersect(which(c['a']==2), which(c['b']==2)))

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388817

You can also subset within the data.frame and then find the rows for it.

nrow(c[a==2 & b==2, ])
# [1] 2

P.S : It is advised not to use c as a variable as it is also a base R function.

Upvotes: 1

Related Questions