Removing individuals from cohort study data based on baseline characteristics

Viewed 115

I have health data from a cohort study with repeated measures, where individuals are seen for multiple yearly follow-up visits. At baseline (visit 0), some individuals are already diagnosed with the disease of interest, while others aren't. As I'm looking at incident cases in my analysis, I need to remove those individual diagnosed as "sick" at visit 0 from my data. How might I do this in the tidyverse? I'm including an example below of the sort of data structure I'll be looking at:

subject_id <- c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5)
visit <- c(0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3)
diagnosis <- c("not sick", "not sick", "not sick", "sick", "sick", "sick", "sick", "sick", "not sick", "not sick", "sick", "sick", "sick", "sick", "sick", "sick", "not sick", "not sick", "not sick", "sick")

cohort <- data.frame(subject_id, visit, diagnosis)
cohort
3 Answers

EDIT: If you want to drop them completely, then:

cohort %>% 
  group_by(subject_id) %>% 
  mutate(Condn = ifelse(visit==0 & diagnosis=="sick",1,0) ) %>% 
  filter(all(Condn==0))

ORIGINAL

We can do:

cohort %>% 
  group_by(subject_id) %>% 
   mutate(Condn = ifelse(visit==0 & diagnosis=="sick",1,0) ) %>% 
   filter(Condn==0) %>% 
   ungroup()  %>% 
   select(-Condn)

With dplyr, you can do:

cohort %>%
 group_by(subject_id) %>%
 filter(first(diagnosis) != "sick")

   subject_id visit diagnosis
        <dbl> <dbl> <fct>    
 1          1     0 not sick 
 2          1     1 not sick 
 3          1     2 not sick 
 4          1     3 sick     
 5          3     0 not sick 
 6          3     1 not sick 
 7          3     2 sick     
 8          3     3 sick     
 9          5     0 not sick 
10          5     1 not sick 
11          5     2 not sick 
12          5     3 sick   

Or:

cohort %>%
 group_by(subject_id) %>%
 filter(diagnosis[row_number() == 1] != "sick")

Thanks to all for their advice. @tmfmnk and @NelsonGon both provided options that worked for this task.

I recently moved from SAS to R, and this was extremely helpful.

Related