[General] What's the best way to structure my 'for' loop code within an 'if' statement so that I don't repeat all the code?

Hi everyone,

This is a bit basic, but I'd like to learn the best practice. I have a very long chunk of code, and sometimes it needs to exist within a for loop, depending on whether a certain condition is met (for example, setting a variable my_answer to "YES". )

If my_answer is not "YES", then I want to execute the code, but not within the loop.

My current understanding is to paste that exact same (long) block of code after else since the initial condition is not met....but this doubles the size of my code. Is there some better way of doing this than the way I'm describing:

my_answer <- c("YES") 

  for(i in 1:1000){
    ###very long code####
    ###it will be looped over 1000 times####
} else {
    ###very long code####
    #Not looped###


Would it make sense to put the for loop outside of the if and use the if to set the iterations of the loop to either 1 or 1000.

if(my_answer  == "yes") {
  top <- 1000
} else {
  top <- 1
for ( i in 1:top) {
  very long code

Thanks @FJCC!

This is a great solution and one that I can make use of in my code. Specifically, I like that when not making use of the loop, for(i in 1:1) works beautifully. Marked as solved.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.