jeudi 27 juillet 2017

Improve my coding "for loop"

The following is a simple loop to insert a new column in a data frame after checking a specific condition (if 2 consecutive rows have the same value). The code works just fine but I would like to improve my coding skills so I ask for alternative solutions (faster, more elegant). I checked previous threads on the topic and learned a lot but I am curious about my specific case. Thanks for any input.

vector<-1
vector_tot<-NULL

  for(i in 1:length(dat$Label1))
  { 
     vector_tot<-c(vector_tot,vector)
     if(dat$Label1[i]==dat$Label1[i+1]){
    vector<-0  
    }
    else {
      vector<-1
      }
      }


dat$vector<- vector_tot

Aucun commentaire:

Enregistrer un commentaire