tf <-tempfile()
writeLines("DrugStart,HN,Blood_date,Results
10/10/2015,1234,01/10/2010,90
10/10/2015,1234,01/10/2011,80
10/10/2015,1234,01/10/2012,70
10/10/2015,1234,01/10/2013,60
10/10/2015,1234,01/10/2014,50
10/10/2015,1234,01/10/2015,40
10/10/2015,1234,01/10/2016,30
10/10/2015,1234,01/10/2017,20
10/10/2015,1234,01/10/2018,19
10/10/2015,1234,01/10/2019,19
10/10/2015,1234,01/10/2020,18
10/10/2015,1234,01/10/2021,17
NA,4567,01/10/2010,90
NA,4567,01/10/2011,80
NA,4567,01/10/2012,70
NA,4567,01/10/2013,60
NA,4567,01/10/2014,50
NA,4567,01/10/2015,40
NA,4567,01/10/2016,30
NA,4567,01/10/2017,20
NA,4567,01/10/2018,19
NA,4567,01/10/2019,19
NA,4567,01/10/2020,18", tf)
library(tidyverse)
library(lubridate)
df<- readr::read_csv(tf) %>%mutate_if(is.character,lubridate::dmy)
myprocess<-function(d,...){
mds<-min(d$DrugStart,na.rm=FALSE)
if(!is.na(mds)){
return(filter(d,
Blood_date <= mds))
} else {
mw20 <- min(which(d$Results<=20))
return(slice(d,
1:mw20))
}
}
df %>% group_by(HN) %>% group_map(myprocess)