R: Break for loop

Rui Morais picture Rui Morais · May 21, 2011 · Viewed 242.8k times · Source

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,])
       }
      }
    }

Answer

Sacha Epskamp picture Sacha Epskamp · May 21, 2011

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
        }   
    }
}