67

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,])
       }
      }
    }
zx8754
  • 52,746
  • 12
  • 114
  • 209
Rui Morais
  • 689
  • 1
  • 6
  • 6
  • 11
    If you're having a problem with this code, note that `in` is a reserved word, so you can't use it as a variable name. – Hong Ooi May 22 '11 at 05:03

2 Answers2

106

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
        }   
    }
}
Community
  • 1
  • 1
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
24

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,])
    }
}
msikd65
  • 427
  • 1
  • 5
  • 11
  • Thank you very much! I think its true, it breaks. My doubts where mainly because I'm comparing two dataframes with about 30000 rows and to check if there are new data rows or deleted rows. Its taking hours to get it working done. I'm doing it with loops like this and it might be a away of doing it more faster? Thanks again for your precious help – Rui Morais May 22 '11 at 14:19
  • 3
    you need to vectorize your logic. lets say you have a vector of numbers of 1-10 `vector = c(1:10)` and you want to subtract 1 from every element. Dont do it with a for loop! Just simply do the following `vector = vector - 1`. You will have to rewrite everything and rethink your logic. look at `?apply` it is your good friend. Post more of your code and with reproducible data maybe you can get better help. – msikd65 May 22 '11 at 14:41