0
newdf=data.frame(id=c(1,3,1,2,1,3,2,2),
                 dates=c("2020-05-19","2020-05-02","2020-05-20","2020-05-09","2020-05-21","2020-05-04","2020-05-10","2020-05-11"),
                 antibiotic=c("Yes","No","Yes","Yes","Yes","No","Yes","Yes"),
                 culture=c("2020-05-15","","","","","","2020-05-11","2020-05-12"),
                 culture1=c("","","","","","","2020-05-08",""))

newdf$dates=as.Date(newdf$dates)
newdf$culture=as.Date(newdf$culture)
newdf$culture1=as.Date(newdf$culture1)
newdf=newdf[order(newdf$dates),]

#I think this doesn't work well
testdata=newdf %>% group_by(id) %>%
  mutate(culture_sent = case_when((dates >= min(culture,culture1,na.rm = T)) & (antibiotic == 'Yes') ~ 'Yes', TRUE ~ 'No'))

I want to create new categorical variable ('Yes', 'No') call 'culture_sent'. If minimum date of culture and culture1 less than dates (a date variable) & antibiotic 'Yes', then I want to put 'Yes' for that particular patient (otherwise 'No'). I tried a method but I believe, it doesn't not give the answer that I want. Could you please suggest a method to do this? I have attached image of data set herewith.
enter image description here

1 Answers1

1

You can try with if_else -

library(dplyr)

newdf %>%
  mutate(culture_sent = if_else(dates > pmin(culture, culture1, na.rm = TRUE) & 
                            antibiotic == 'Yes', 'Yes', 'No', missing = 'No'))

#  id      dates antibiotic    culture   culture1 culture_sent
#2  3 2020-05-02         No       <NA>       <NA>           No
#6  3 2020-05-04         No       <NA>       <NA>           No
#4  2 2020-05-09        Yes       <NA>       <NA>           No
#7  2 2020-05-10        Yes 2020-05-11 2020-05-08          Yes
#8  2 2020-05-11        Yes 2020-05-12       <NA>           No
#1  1 2020-05-19        Yes 2020-05-15       <NA>          Yes
#3  1 2020-05-20        Yes       <NA>       <NA>           No
#5  1 2020-05-21        Yes       <NA>       <NA>           No

pmin(culture, culture1, na.rm = TRUE) would give you the minimum date between culture and culture1.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213