Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Break for loop

Tags:

for-loop

r

break

Can you confirm if the next break cancels the inner for loop?

   for (out in 1:n_old){       id_velho <- old_table_df$id[out]       for (in in 1:n)       {        id_novo <- new_table_df$ID[in]        if(id_velho==id_novo)        {         break        }else         if(in == n)        {        sold_df <- rbind(sold_df,old_table_df[out,])        }       }     } 
like image 320
Rui Morais Avatar asked May 21 '11 15:05

Rui Morais


People also ask

How do you break loop in R?

When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).

How do you stop a loop in a condition in R?

A break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. In a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

How use next and break in R?

The basic Function of Break and Next statement is to alter the running loop in the program and flow the control outside of the loop. In R language, repeat, for and while loops are used to run the statement or get the desired output N number of times until the given condition to the loop becomes false.


2 Answers

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10) {     for (j in 1:10)     {         for (k in 1:10)         {             cat(i," ",j," ",k,"\n")             if (k ==5) break         }        } } 
like image 114
Sacha Epskamp Avatar answered Sep 24 '22 12:09

Sacha Epskamp


your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n) {     if (in == n)         #add this statement     {         "sorry but the loop did not break"     }      id_novo <- new_table_df$ID[in]     if(id_velho==id_novo)     {         break     }     else if(in == n)     {         sold_df <- rbind(sold_df,old_table_df[out,])     } } 
like image 32
msikd65 Avatar answered Sep 25 '22 12:09

msikd65