#######################################################################################
### Purpose   : To create and prepare the reference data for rcVPC
### Created by: Moustafa M.A. Ibrahim
### Created   : 2024-11-10
#######################################################################################
## Needed input: 

# 1) observed_data is the observations dataset
# 2) EBE_data is the final Empirical Bayes Estimates of the PK parameters. 

observed_data <-read.table('obsdata.csv',header=T,sep=",")
EBE_data <-read.table('EBEs.csv',header=T,sep=",")

#######################################################################################
############################# Creating reference dataset ##############################

## Manipulating interesting covariates other than the time variable:
# Create a reference data where AMT and ADDL are set to 600 mg and 15, respectively 

ref_data <- Observed_data %>%
  mutate(AMT = ifelse(MDV==1, 600,0)) %>%
  mutate(ADDL = ifelse(MDV==1, 15,0)) %>%
  arrange(REF)

write.csv(ref_data, file="refdata.csv",quote=FALSE, row.names=FALSE, na=".")

## Manipulating the time variable to produce PK metrics:
# Create a reference data where time for PD endpoint(TYPE==2)is set to end of treatment, and ADDL is set to 15. 

refdata_time<-observed_data %>% 
  left_join(EBE_data,by = "ID") %>% # add EBEs
  mutate(TIME = ifelse((TYPE==2 & TIME>0), 2688,TIME)) %>%
  mutate(ADDL = ifelse(MDV==1, 15,0)) %>%
  group_by(ID) %>%
  arrange(ID,TIME,MDV)

write.csv(refdata_time, file="refdata_time.csv",quote=FALSE, row.names=FALSE, na=".")