R语言if..else语句

一个if语句可以跟随一个可选的else语句,当布尔表达式为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语句中的代码块。

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"

注:这里 “Truth” 和 “truth” 是两个不同的字符串。

if…else if…else语句

一个if语句可以跟随一个可选的else if...else语句,这对使用单个if...else else语句来测试各种条件非常有用。

当使用ifelse if, else语句时要注意几点。

  • if语句可以有零个或一个else,但如果有else if语句,那么else语句必须在else if语句之后。
  • if语句可以有零或多else if语句,else if语句必须放在else语句之前。
  • 当有一个else if条件测试成功,其余的else...ifelse将不会被测试。

语法

在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"

        原文作者:R语言教程
        原文地址: https://www.yiibai.com/r/r_if_else_statement.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞