2017-10-04 5 views
0

複数のif文をwhileループ内で一緒にネストすることは可能ですか?whileループ内の複数のif文をネストするR

私は彼らに自分自身を公開する簡単な例を作成しようとしています:

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で立ち往生し、永遠に実行したい取得し続けます。どうすればこれを避けることができますか?

+0

あなたはあなたの答えを持っている - あまりにも多くの '{' 'sがありました。これを追加することで、コードの書式設定にもっと注意を払うことをお勧めします。スペースやインデントを正しく使用すると、そのような問題にぶつかりにくくなります。 – dww

+0

あなたは上記のコードを正しくフォーマットして、あなたが意味するものを知っているでしょうか?または例を挙げてください。 上記の形式は私の教授のアプローチに従いますが、私はあなたのより明確な方法を教えてください。 – Jeremy

+0

ハドリーのスタイルガイドはhttp://adv-r.had.co.nz/Style.htmlまたはGoogleのスタイルガイドはhttps://google.github.io/styleguide/Rguide.xmlです。 1つを選び、それに固執する。 – dww

答えて

0

後に余分な{を持っていました。あなたもちょうどiかどうかをチェックすることによって、あなたのelse ifを簡素化することができますしかし

3が(すでにiが、それはあなたがi > 6かどうかを確認最初if条件を失敗から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 
1

@Alex Pで述べたようにあなたは、余分な{を持っている最初の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") 
} 
関連する問題