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

Rui Barradas ruipbarradas at sapo.pt
Sun Dec 4 12:59:47 CET 2016


Hello,

Please post in plain text not in HTML, like the posting guide asks you to.
To give a data example use ?dput, like this:

dput(head(trboot3, 20))  # paste the output of this in your mail

If you have a sample of trboot4 please also use dput to post it.

Finally, I don't understand your second condition, what does "same 
number one below another in a row" mean? Is it "below" (different rows) 
or in the same row? And you say to keep the first and change the rest. 
Once again, is it the rest of the row?

Anyway I believe I have already found a problem in your code. In

for (i in 2:valboot-1)

you should try to see what exactly is 2:valboot-1. [Tip: it starts with a 1]
Maybe you meant 2:(valboot-1).

Rui Barradas

Em 04-12-2016 10:08, Ashwini Patil escreveu:
> 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]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list