Filter rows based on values of a column

Viewed 17

Here's the sample dataset:

sample  <- data.frame(ID =  c(100,100,101,101,102,102,103,103), flag = c(0,0,1,1,0,1,0,0))


   ID flag
1 100    0
2 100    0
3 101    1
4 101    1
5 102    0
6 102    1
7 103    0
8 103    0

I would like to filter the rows, based on the value in flag column, and keep only the IDs for which "all" the corresponding flag values are 0. In this case, the remaining rows are 1, 2, 7, and 8.

1 Answers

A tidyverse solution:

# Load packages
require("tidyverse")
#> Loading required package: tidyverse

# Generate data
sample  <- data.frame(ID =  c(100,100,101,101,102,102,103,103), flag = c(0,0,1,1,0,1,0,0))

# Filter based on flag.
sample %>%
  group_by(ID) %>%
  filter(all(flag == 0))
#> # A tibble: 4 x 2
#> # Groups:   ID [2]
#>      ID  flag
#>   <dbl> <dbl>
#> 1   100     0
#> 2   100     0
#> 3   103     0
#> 4   103     0

Created on 2022-09-20 by the reprex package (v2.0.1)

Related