[R] How to subtract the counter i in for loop?

David Winsemius dwinsemius at comcast.net
Fri Nov 30 00:11:22 CET 2012


On Nov 29, 2012, at 1:55 PM, C W wrote:

> Hi list,
> I am writing a for loop that looks like this:
> samples<-rep(NA,10)
> x <- rep(c(111, 225), 5)
> for(i in 1:10){
>    If(x[i]<200){
>         samples[i] <- x[i]
>     }else{
>     i=i-1

If you expected the else clause to assign something to the samples vector, you are mistaken.

>    }
> }
> 
> The problem is that the returning vector still contains NA,  I think the i
> in "else" is not getting subtracted.  How should I get it to work? 

You could start by telling us what you wanted to happen. You can change the index of a for loop inside the body, but it will not "back up the process" since at the end of the loop the next "i" will not depend on what you changed it to inside the loop.

-- 

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list