目录

if...else statement

if语句后面可以跟一个可选的else语句,该语句在布尔表达式为false时执行。

语法 (Syntax)

在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 block代码if block ,否则将执行代码else block

流程图 (Flow Diagram)

R if ... else语句

例子 (Example)

x <- c("what","is","truth")
if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}

编译并执行上述代码时,会产生以下结果 -

[1] "Truth is not found"

这里“真理”和“真理”是两个不同的字符串。

if...else if...else (The if...else if...else Statement)

if语句后面可以跟一个else if...else语句,这对于使用单个if ... else if语句测试各种条件非常有用。

当使用ifelse ifelse语句时,要记住几点。

  • 一个if可以有0或者else一个, if是的else ,它必须在else if之后。

  • if可以有零到多个,并且它们必须在else之前。

  • 一旦else if成功, else if任何其他else if else不会被测试。

语法 (Syntax)

在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.
}

例子 (Example)

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"
↑回到顶部↑
WIKI教程 @2018