# Keeping groups based on the row count of a second column

I have the following code that aims to filter those pid (1 and 4) that have at least before_threshold (2) rows with a value of before in the day_type column and at least after_threshold (2) rows with a value of after in the same day_type column.

Is there a more succinct way of doing this using the tidyverse packages?

library(tidyr)

before_threshold = 2
after_threshold = 2
data <- data.frame(pid = c(rep("1", 5), rep("2",5), rep("3", 1), rep("4", 4)),
day_type = c(rep("before", 3), rep("after", 2), rep("before", 5), rep("after", 1), rep("before", 2), rep("after", 2)),
stringsAsFactors = F)

data <- data %>%
group_by(pid) %>%