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

Ashwini Patil ash369ster at gmail.com
Sun Dec 4 11:08:27 CET 2016


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

V7  V8  V90   1   0-1  1   -1-1  1   -1-1  0   -1-1  0   -1-1  0
-1-1  0   -1-1  1   -10   1   -10   1   -1-1  0   00   0   00   0   00
  0   00   0   00   -1  00   -1  -10   0   00   1   00   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 below another in a 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  V90   1   0-1  0   -10   0   00   0   00   0   00   0   00   0
  00   1   00   0   00   0   0-1  0   00   0   00   0   00   0   00
0   00   -1  00   0   -10   0   00   1   00   0   0


Thank you!

	[[alternative HTML version deleted]]



More information about the R-help mailing list