[R] crazy loop error.

Petr Savicky savicky at praha1.ff.cuni.cz
Tue Jan 25 09:05:03 CET 2011


On Mon, Jan 24, 2011 at 11:18:35PM +0100, Roy Mathew wrote:
> Thanks for the reply Erik, As you mentioned, grouping consecutive elements
> of 'a' was my idea.
> I am unaware of any R'ish way to do it. It would be nice if someone in the
> community knows this.
> 
> The error resulting in the NA was pretty easy to fix, and my loop works, but
> the results are still wrong (new script below).
> Ideally it should print single "hello" for the single letters and grouped '3
> hellos' for the fives, grouped '2 hellos' for the sixes etc.
> 
> Based on the run results, if the value of n is being tracked, it changes
> quite unpredictably.
> Can someone explain how the value of n changes from end of the loop to the
> top without anything being done to it?

Hi.

A for-loop in R is different from a for-loop in C. It is similar
to foreach loop in Perl. If v is a vector, then

  for (n in v)

first creates the vector v and then always performs length(v) iterations.
Before iteration i, n is assigned v[i] even if n is changed in the
previous iteration.

If you want to control the loop variable during execution, it is possible
to use a while loop, where you have full control. While loop may be better
also if v has a very large length, since, for example

  for (n in 1:1000000)

creates a vector of length 1000000 in memory.

It should also be noted that the for-loop

  for (n in 1:k)

performs 2 iterations, if k is 0, since 1:0 is a vector of length 2.
If k may be 0, then it is better to use

  for (n in seq(length=k))

since seq(length=0) has length 0.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list