在R中的while循环中嵌套多个if语句

时间:2017-10-04 00:12:12

标签: r if-statement while-loop nested-loops

是否可以在while循环中将多个if语句嵌套在一起?

我正在尝试创建一个简单的例子,只是为了让自己暴露给他们:

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

我的示例代码一直停留在i = 7并希望永远运行。我怎么能避免这个?

2 个答案:

答案 0 :(得分:1)

在第一个{

之后您还有一个else
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")
}

答案 1 :(得分:0)

如@Alex P所述,你有一个额外的{

但是,您也可以通过检查else if是否大于等于i来简化3(您已经知道i将小于或等于6它在第一个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")
}

<强>输出:

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