How do I keep every ID which meet a condition at least once?

Viewed 25

How do I keep every ID which meet a condition at least once?

I have a df with repeated measurements. Now i want to keep all rows of the individuals that meet a condition at least once. I tried a dplyr group_by but i always only end up with the rows that fulfill the condition and loose all other measurements of that individual.

dat2 <- dat1 %>%
  group_by(id) %>%
  filter(category=="blood") %>%
  ungroup()

Thanks in advance!

1 Answers

Add an "|" (ALT-124) to add explicit OR conditions to the filter. Any of these things being true will return the entire line.

dat1 %>%
  group_by(id) %>%
  filter(category=="blood" | condition2 == TRUE | condition 3 %in% c(1, 2, 3)) %>%
  ungroup()

You could also use any():

dat1 %>%
  group_by(id) %>%
  filter(any(category=="blood", condition2 == TRUE, condition3 %in% c(1, 2, 3))) %>%
  ungroup()

The complement to this is & (AND) and the function all(), which return only rows which all conditions are true

Related