dimanche 25 mars 2018

for-loop through ID-List & counting Values

I hope someone can help me with my problem, I know using two for-loops is not very efficient but that was my first solution. I have a data frame (AllPat) with eye-patients (patient-id, date and visit ->'o'perations or 'c'heckups)

#Pat    Date        Visit    
#1,l    2015-03-30    c        
#1,l    2015-06-03    o        
#1,l    2015-07-01    o        
#1,l    2015-07-20    c    
#1,l    2016-03-16    o        
#1,l    2016-04-13    o        
#1,l    2016-05-09    c           
#2,l    2014-12-23    c 
#2,l    2015-01-21    o        
#2,l    2015-03-16    c    
#2,l    2015-11-23    o        

And I want to count the operation-blocks for each patient-id (before and after a checkup)

#Pat    Date        Visit    Block
#1,l    2015-03-30    c        
#1,l    2015-06-03    o        1
#1,l    2015-07-01    o        2
#1,l    2015-07-20    c    
#1,l    2016-03-16    o        1
#1,l    2016-04-13    o        2
#1,l    2016-05-09    c           
#2,l    2014-12-23    c 
#2,l    2015-01-21    o        1
#2,l    2015-03-16    c    
#2,l    2015-11-23    o        1

and that's the current code:

for(i in unique(AllPat$Pat)){
op <- 0
for(j in AllPat$Pat){
  if(i == j) {
    if(AllPat$Visit[AllPat$Pat == j] == "o") {
      AllPat$Block[AllPat$Pat == j] <- op
      op <- op+1
    }
    else op<-0
  }
}
}

my problem is, that the values in $Block only get visible if I sort them by hand in the view of the data frame, maybe someone has a better solution and can help me

Aucun commentaire:

Enregistrer un commentaire