[R] crazy loop error.
Petr Savicky
savicky at praha1.ff.cuni.cz
Mon Jan 24 21:28:47 CET 2011
On Mon, Jan 24, 2011 at 07:16:58PM +0100, Roy Mathew wrote:
> Dear R-users,
> This is a loop which is part of a bigger script. I managed to isolate the
> error in this loop and simplified it to the bare minimum and made it
> self-contained.
>
> a<-c(2,3,4,5,5,5,6,6,6,7)
>
> for(n in 1:10)
> {
> print(paste("n: ",n))
> z1<-a[n]
> #make a list container
> ldata<-list()
> t=1
>
> while(z1==a[n])
> {
>
> #add dataframes to list
> ldata[[t]]<-paste("hello")
>
> n=n+1
> t=t+1
>
> }
> print("------End of while loop-------")
>
> for(y in 1:length(ldata))
> {
> print(ldata[[y]])
> }
>
> print(paste("n: ",n))
> print("******End of for loop********")
> }
>
>
> This script has a vector "a", for-loop, and a nested while-loop.
> The for-loop runs from 1 to length of a. At every number of a, it enters the
> while-loop and a hello is saved into list ldata.
> If the next number in the vector a is a different number from previous then
> the while-loop is exited and saved hello is printed.
> If the next number in vector a is same as before then it loops inside the
> while-loop and several hellos are printed together.
>
> Then run-time error is
>
> Error in while (z1 == a[n]) { : missing value where TRUE/FALSE needed
>
> Thats because an NA creeps in somewhere. The problem can be seen far before
> that. The full output from the run is below.
> A lot of stuff was printed to help with the debugging. At n=4, there are
> three repeats of 5, therefore hello is printed 3 times. n then becomes 7.
> Then when the for-loop returns to top, n miraculously becomes 5. Hows
> that!!??
Hi.
The for-loop "for (i in 1:k)" uses an internal index, which counts
the repetitions. This is necessary, since the control over a loop
like "for (i in c(1,1,1,1))" cannot be based on the variable i only.
Hence, changing i does not influence the next iteration of the loop.
For example, the following loop always makes m*n repetitions, although
using the same variable in nested loops is definitely not suggested.
m <- 3
n <- 5
for (i in seq(length=m)) {
for (i in seq(length=n)) {
cat("*")
}
cat("\n")
}
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list