'Count number of rows matching >1 criteria

I have a dataframe with two columns, as follows:

A<-c(4,4,4,3,2,4,1)
B<-c(4,4,2,31,3,1,1)
data<-data.frame(A,B)

I know I can use grep() to search for the number of times a row matches one criteria (e.g. length(grep(4,A)) would count that there are 4 times theres a 4 in column A.

How can I get R to count the number of rows that match TWO criteria--e.g. "how many rows have a "4" in column A AND a "2" in column B.

C<-c("hat", "hat", "coat")
D<-c("shoe", "sock", "glove")
data2<-data.frame(C,D)

Ideally, I'd like something that can work for strings too. In this instance, e.g., how many rows contain "hat" in C and "sock" in D?

(This is essentially the equivalent of the COUNTIFS function in Excel.)

r


Solution 1:[1]

You may try

library(dplyr)
data %>%
  filter(A == 4, B == 2) %>%
  nrow

[1] 1

data2 %>%
  filter(C == "hat", D == "sock") %>%
  nrow

[1] 1

where

data %>%
  filter(A == 4, B == 2)

  A B
1 4 2

data2 %>%
  filter(C == "hat", D == "sock")

    C    D
1 hat sock

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Park