mardi 31 mai 2016

for if/elseif loop not working in R

I want to calculate the sum of the following logic below. Basically add one to numTrade whenever the element switch between 0, 1, -1, and treat consecutive elements as 0, such that (0, 1, 1, 1) is counted as 1 and (1,0,-1,1) is counted as 3.

numTrade should return total of 4, but instead it returns 3. Can someone please explain why?

numTrade<-0

numUnits<-c(0,1,0,-1,1,1,-1)

for(i in 2:length(numUnits)){
  if(numUnits[i]>0 & numUnits[i-1]<0){
    numTrade<-numTrade+1
  }
  else if(numUnits[i]<0 & numUnits[i-1]>0){
    numtrade<-numTrade+1
  }
    else if(numUnits[i]!=0 & numUnits[i-1]==0){
      numTrade<-numTrade+1
    } 
      else {
        numTrade<-numTrade+0
      }
  print(numTrade)
} 

Aucun commentaire:

Enregistrer un commentaire