Search code examples
rif-statementwhile-loopnested-loops

Nesting multiple if statements inside a while loop in R


Is it possible to nest multiple if statements together within a while loop?

I'm attempting to create a simple example just to expose myself to them:

i <- 1 
while(i <=10) {
if(i > 6){
cat("i=",i,"and is bigger than 6.\n")
}else{if(3<i & i<6){
cat("i=",i,"and is between 3 and 6.\n")
}else{  
cat("i=",i,"and is 3 or less.\n")
}
i<-i+1
cat("At the bottom of the loop i is now =",i,"\n")
}

My sample code keeps getting stuck at i=7 and wants to run forever. How can I avoid this?


Solution

  • As mentioned by @Alex P you have an extra {.

    However you can also simplify your else if by just checking if i is greater than equal 3 (you already know i will be less than or equal to 6 from it failing the first if condition where you check if i > 6):

    i <- 1 
    while(i <=10) {
        if(i > 6) {
            cat("i =", i, "and is bigger than 6.\n")
        } else if(i >= 3) {
            cat("i =", i ,"and is between 3 and 6 inclusive.\n")
        } else {  
            cat("i =", i ,"and is less than 3.\n")
        }
        i = i + 1
        cat("At the bottom of the loop i is now =", i ,"\n")
    }
    

    Output:

    i = 1 and is less than 3.
    At the bottom of the loop i is now = 2 
    i = 2 and is less than 3.
    At the bottom of the loop i is now = 3 
    i = 3 and is between 3 and 6 inclusive.
    At the bottom of the loop i is now = 4 
    i = 4 and is between 3 and 6 inclusive.
    At the bottom of the loop i is now = 5 
    i = 5 and is between 3 and 6 inclusive.
    At the bottom of the loop i is now = 6 
    i = 6 and is between 3 and 6 inclusive.
    At the bottom of the loop i is now = 7 
    i = 7 and is bigger than 6.
    At the bottom of the loop i is now = 8 
    i = 8 and is bigger than 6.
    At the bottom of the loop i is now = 9 
    i = 9 and is bigger than 6.
    At the bottom of the loop i is now = 10 
    i = 10 and is bigger than 6.
    At the bottom of the loop i is now = 11