We can do a group by filter
. Grouped by 'ID', filter
all groups where the 'Event' doesn't have 1
library(dplyr)
df1 %>%
group_by(ID) %>%
filter( all(Event != 1))
-output
# A tibble: 4 x 3
# Groups: ID [3]
# ID Drugs Event
# <int> <chr> <int>
#1 345 Bigunaides 2
#2 345 SGLT2 3
#3 456 SGLT2 3
#4 567 DPP4 4
Or another option is
df1 %>%
group_by(ID) %>%
filter(!1 %in% Event)
-output
# A tibble: 4 x 3
# Groups: ID [3]
# ID Drugs Event
# <int> <chr> <int>
#1 345 Bigunaides 2
#2 345 SGLT2 3
#3 456 SGLT2 3
#4 567 DPP4 4
NOTE: Both solutions work
data
df1 <- structure(list(ID = c(123L, 123L, 123L, 234L, 234L, 345L, 345L,
456L, 567L), Drugs = c("Insulin", "Bigunaides", "SGLT2", "Insulin",
"SGLT2", "Bigunaides", "SGLT2", "SGLT2", "DPP4"), Event = c(1L,
2L, 3L, 1L, 3L, 2L, 3L, 3L, 4L)), class = "data.frame", row.names = c(NA,
-9L))