[R] for loop help

Hans-Jörg Bibiko bibiko at eva.mpg.de
Fri Apr 11 07:57:13 CEST 2008


On 11.04.2008, at 05:38, <Bill.Venables at csiro.au>  
<Bill.Venables at csiro.au> wrote:

>> ?`break`
>> ?`next`
>>
>
>
>> for(i in 1:13) {
>>
>     if(i < 13) next
>     print("Hello!\n")
>     }
> [1] "Hello!\n"
>
>>
>>
>
> I am trying to find a solution in R for the following C++ code that
> allows
> one to skip ahead in the loop:
>
> for (x = 0; x <= 13; x++){
>  x=12;
>  cout << "Hello World";
> }
>
> Note that "Hello World" was printed only twice using this C++ loop. I
> tried to do the same in R:
>
> for(i in 1:13){
>  i=12
>  print("Hello World")
> }
> It doesn't work as I expected, i.e., this R loop prints "Hello  
> World" 13
> times.
>

Maybe to understand this try:
for(i in 1:13){i <- rnorm(1);print(i)}

You cannot change the seq in a for loop as you can in C, Perl, etc.
The variables i in for() and the i within the statement are not the  
same. Thus you only can query i (see Bill's hint).

see also ?Control; last paragraph in 'Details'

--Hans



More information about the R-help mailing list