## 
## Data pull and export for Forskermaskinen
## 
## Exports are made in REDCap instead
## 
## Data set is made here, not in REDCap, as data here is better organised.
## 


dta<-read.csv("/Volumes/Data/exercise/source/background.csv",colClasses = "character", na.strings = c("NA","","unknown"))

export<-dta[,c("pase_0",
               "age",
               "sex",
               "civil",
               "smoker", 
               "rtreat",
               "alc",
               "afli",
               "hypertension",
               "diabetes",
               "mrs_0",
               "nihss_c",
               "thrombolysis",
               "pad", 
               "thrombechtomy", 
               "ami", 
               "tci",
               "rdate",
               "cpr",
               "rnumb",
               "height",
               "weight",
               "weight_est",
               "inc_time",
               "compliant",
               "mrs_1",
               "mrs_6",
               "pase_6",
               "visit_1",
               "visit_6")]

export$diabetes[is.na(export$diabetes)]<-"no"
export$diabetes[is.na(export$hypertension)]<-"no"
export$thrombolysis[is.na(export$thrombolysis)]<-"no"
export$thrombechtomy[is.na(export$thrombechtomy)]<-"no"
export$pad[is.na(export$pad)]<-"no"
export$ami[is.na(export$ami)]<-"no"
export$inc_time[export$inc_time<0]<-0
export$compliant<-as.numeric(factor(export$compliant))
export$rdate<-as.Date(export$rdate)
# export$mrs_0[export$mrs_0==3]<-NA

export <- export|>
  mutate(any_rep=factor(ifelse(thrombolysis=="yes"|thrombechtomy=="yes","yes","no")), # If not noted, no therapy was received
         weight=ifelse(is.na(weight),weight_est,weight))|>
  select(-c(weight_est))

write.csv(export|>select(c(rnumb,rtreat)),"/Volumes/Data/SDS upload/study_treatment.csv",row.names = FALSE)
write.csv(export,"/Volumes/Data/SDS upload/data_all.csv",row.names = FALSE)
write.csv(export|>select(-c(rtreat)),"/Volumes/Data/SDS upload/background.csv",row.names = FALSE)
