R: Break for loop

核能气质少年 提交于 2020-01-09 04:45:08

问题


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


来源:https://stackoverflow.com/questions/6082655/r-break-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!