[R] Trying to perform an inner loop a random number of times

jim holtman jholtman at gmail.com
Thu Apr 28 05:31:39 CEST 2011


What exactly are you trying to accomplish?  A little debugging might
show you what the problem is.  I put the following statement in the
loop right after the assignment to 'newrow':

print(newrow)

What I saw is that you never reset 'iter' and once it reached a
maximum length, you were continuing to use it so all the dataframes
has the same size after a point.  You can see it in your data in that
all the last ones have a length of 3.

So your loop is doing exactly what you 'wrote' it to do.  If you are
not getting the results you expect, then learn how to debug.  I put a
'browser()' call in you loop and this let me see what was going on.
You need to learn to instrument your scripts so that you can trace the
progress and see if it is working correctly.

On Wed, Apr 27, 2011 at 10:33 PM, Galen Moore <galen.a.moore at gmail.com> wrote:
> Grateful for any hints as to why I'm not getting the inner loop to cycle the
> expected number of times.
>
>
>
> Code and one run's results below.
>
>
>
> Thanks,
>
>
>
> Galen
>
>
>
>
>
>> # source("looptest.r")
>
>> sp<-numeric()
>
>> iter<-numeric()
>
>> rn<-numeric()
>
>> ds<-data.frame(sp, iter, rn)
>
>>
>
>> for (sp in c(1:6)) {
>
> +            i<-1
>
> +            while (i <= 5) {
>
> +                     rn<-0
>
> +                     rn<-round(runif(1, 1, 5))
>
> +                     if (i > rn) { break }
>
> +
>
> +                     else {
>
> +                         iter[i]<-i
>
> +                         newrow<-data.frame(sp, iter, rn)
>
> +                         i<-( i + 1)
>
> +                         }
>
> +                  }
>
> +                  ds<-rbind(ds, newrow)
>
> +             }
>
>> print(ds)
>
>   sp iter rn
>
> 1   1    1  3  >> sp #1 should appear 3x, not 2x
>
> 2   1    2  3
>
> 3   2    1  5  >> sp #2 should appear 5x, not 3x
>
> 4   2    2  5
>
> 5   2    3  5
>
> 6   3    1  5  >> sp #3 should appear 5x, not 3x
>
> 7   3    2  5
>
> 8   3    3  5
>
> 9   4    1  4  >> sp #4 should appear 4x, not 3x
>
> 10  4    2  4
>
> 11  4    3  4
>
> 12  5    1  3  >> this actually works as expected, but not 2x as with sp #1
>
> 13  5    2  3
>
> 14  5    3  3
>
> 15  6    1  5  >> sp #6 should appear 5x, not 3x
>
> 16  6    2  5
>
> 17  6    3  5
>
>>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list