R: Break for loop

2019-01-11 05:22发布

问题:

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

回答1:

Well your code is not reproducable so we 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
        }   
    }
}   


回答2:

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


标签: r for-loop break