R: Break for loop

RFor LoopBreak

R Problem Overview


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

R Solutions


Solution 1 - R

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

Solution 2 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRui MoraisView Question on Stackoverflow
Solution 1 - RSacha EpskampView Answer on Stackoverflow
Solution 2 - Rmsikd65View Answer on Stackoverflow