I am dealing with some patients data in R. I need to calculate the time it takes between the first visit to the last visit for the normal patients, and the time between the first visit to the date of first disease diagnosis for patients who progressed to the disease. I have tried but it didn't work out. I really appreciate if someone could help.
My data looks like "patient", where visit_number = the visit orders, followup_days=days between the first visit to each follow up visit.
patient<-data.frame(patient_ID=c(1,1,2,2,2,3,3,4,4,4),age=c(63,64,60,61,63,61,62,77,77,79),
visit_number=c(1,2,1,2,3,1,2,1,2,3), followup_days=c(0,504,0,390,798,0,379,0,310,621),diagnosis=c(0,0,0,1,1,0,0,0,0,1))
The new data needs to look like "patient1". I need to create a new variable "time".
For patients with a normal status, the time is the length of days between the first visit and the last visit.
For patients with a disease diagnosis (diagnosis=1), the time is the length of days between the first visit, and the FIRST time of the diagnosis of 1.
patient1 <-data.frame(patient_ID=c(1,1,2,2,2,3,3,4,4,4),age=c(63,64,60,61,63,61,62,77,77,79),
visit_number=c(1,2,1,2,3,1,2,1,2,3), followup_days=c(0,504,0,390,798,0,379,0,310,621),
diagnosis=c(0,0,0,1,1,0,0,0,0,1), time=c(504,504,390,390,390,379,379,621,621,621))
Lastly, for the final data set, I would like to only keep the first visit for each patients, with the "time" column added.
new_patient <-data.frame(patient_ID=c(1,2,3,4),age=c(63,60,61,77),
visit_number=c(1,1,1,1), followup_days=c(0,0,0,0),disgonosis=c(0,0,0,0), time=c(504,390,379,621))
Any ideas how to make it happen? Thank you