Filter data frame matching all values of a vector

Viewed 8171

I want to filter data frame x by including IDs that contain rows for Hour that match all values of testVector.

ID <- c('A','A','A','A','A','B','B','B','B','C','C')
Hour <- c('0','2','5','6','9','0','2','5','6','0','2')

x <- data.frame(ID, Hour)
x
   ID Hour
1   A    0
2   A    2
3   A    5
4   A    6
5   A    9
6   B    0
7   B    2
8   B    5
9   B    6
10  C    0
11  C    2

testVector <- c('0','2','5')

The solution should yield the following data frame:

x
       ID Hour
    1   A    0
    2   A    2
    3   A    5
    4   A    6
    5   A    9
    6   B    0
    7   B    2
    8   B    5
    9   B    6

All values of ID C were dropped because it was missing Hour 5. Note that I want to keep all values of Hour for IDs that match testVector.

A dplyr solution would be ideal, but any solution is welcome.

Based on other related questions on SO, I'm guessing I need some combination of %in% and all, but I can't quite figure it out.

3 Answers
Related