1
\$\begingroup\$

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) %>% 
  add_count(pid, day_type) %>% 
  mutate(count_before = ifelse(day_type == "before", n, NA),
         count_after = ifelse(day_type == "after", n, NA)) %>% 
  fill(count_before, .direction = "downup") %>% 
  fill(count_after, .direction = "downup") %>% 
  filter(count_before >= before_threshold & count_after >= after_threshold)

print(data)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.