vendredi 6 avril 2018

for loop and if-else statement in R

I have two date column in dataframe, one is DNA extraction date(DNAextraction) and another is BMI extraction date(BMIextraction). Each pair of twins have more than one BMI extraction date. I want to find which BMI extraction date closest to DNA extraction date, and establish a new column called "DATE". If BMI extraction date closest to DNA extraction date in, DATE equal to "closest", if not DATE equal to BMIextraction`. The following is my code, and I can not get the result what I want.

First, I use as.Date and get the difference between DNAextraction and BMIextraction to know the lowest value.

    A$DNAextraction<-as.Date(A$DNAextraction, "%d/%m/%Y")
    A$BMIextraction<-as.Date(A$BMIextraction, "%d/%m/%Y")
    A$DAYS<-abs(as.numeric(A$BMIextraction-A$DNAextraction))

NEXT, I use for loop to solve my question: z<-NULL for(i in unique(A$KCL_ID)){ RESULT<-A[A$KCL_ID==i] if(RESULT$DAYS[RESULT$KCL_ID==i]<-min(RESULT$DAYS[RESULT$KCL_ID==i])){ RESULT$DATE<-"closest" }else{RESULT$DATE<-RESULT$BMIextraction} z<-rbind(z,RESULT) }

Aucun commentaire:

Enregistrer un commentaire