dimanche 4 décembre 2016

R for skip to the next row if condition met and then another condition to check

I know there are a lot of questions already posted on this but I am unable to apply the solution to my issue.

I have a dataset with many rows and columns. Below is a sample:

V7  V8  V9
0   1   0
-1  1   -1
-1  1   -1
-1  0   -1
-1  0   -1
-1  0   -1
-1  0   -1
-1  1   -1
0   1   -1
0   1   -1
-1  0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   -1  0
0   -1  -1
0   0   0
0   1   0
0   0   0

This data is saved in a matrix trboot3 What I want to do is create a loop whereby two conditions are checked and data is altered. 1. If there is a zero, skip to the next row. 2. If there is same number one after another in the row, keep the first number and change the rest to zero.

Here is my code for the above loop:

trboot4<-trboot3
valboot<-length(trboot3[,1])
for (k in 1:length(trboot3[1,])){
  for (i in 2:valboot-1){
    if (trboot3[k,i]==0) {i<-i+1}
    else{
      if(trboot3[k,i] == trboot3[k,i+1]){
        for (j in i+1:valboot){ if(trboot3[k,j] == trboot3[k,i]){trboot4[k,j]<-0}else{break}
          if(j==valboot){break}
        }
      }
    }
  }
}

I want to save the new matrix in trboot4

basically the above sample should become:

V7  V8  V9
0   1   0
-1  0   -1
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   1   0
0   0   0
0   0   0
-1  0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   -1  0
0   0   -1
0   0   0
0   1   0
0   0   0

Aucun commentaire:

Enregistrer un commentaire