R-if-else-statement

提供:Dev Guides
移動先:案内検索

R-If …​ Elseステートメント

*if* ステートメントの後に、ブール式がfalseの場合に実行されるオプションの *else* ステートメントを続けることができます。

構文

Rで if …​ else ステートメントを作成するための基本的な構文は次のとおりです-

if(boolean_expression) {
  //statement(s) will execute if the boolean expression is true.
} else {
  //statement(s) will execute if the boolean expression is false.
}

ブール式が true と評価された場合、コードの* ifブロック*が実行され、そうでない場合はコードの* elseブロック*が実行されます。

流れ図

R if …​ elseステートメント

x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

[1] "Truth is not found"

ここで、「真実」と「真実」は2つの異なる文字列です。

if …​ else if …​ elseステートメント

*if* ステートメントの後にオプションの *else if ... else* ステートメントを続けることができます。これは、単一のif ... else ifステートメントを使用してさまざまな条件をテストするのに非常に便利です。
*if* 、 *else if* 、 *else* ステートメントを使用する場合、留意すべき点はほとんどありません。
  • if には0個または1個の else があり、 else if の後に来る必要があります。
  • if には0個以上の else if’s があり、else ifの前に来る必要があります。
  • else if が成功すると、残りの else if または else はテストされません。

構文

Rで if …​ else if …​ else ステートメントを作成するための基本的な構文は-

if(boolean_expression 1) {
  //Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
  //Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
  //Executes when the boolean expression 3 is true.
} else {
  //executes when none of the above condition is true.
}

x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found the first time")
} else if ("truth" %in% x) {
   print("truth is found the second time")
} else {
   print("No truth found")
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

[1] "truth is found the second time"