登录
首页精彩阅读R语言if...else语句
R语言if...else语句
2017-06-14
收藏

R语言if...else语句

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 代码块将被执行。

流程图

示例

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 if 语句来测试各种条件非常有用的。

当使用 if , else if , else 语句有几点要牢记。

if 语句后可以有零或一个 else 语句,它必须出现在 else if语句之后。

一个 if 语句 可有0到多个 else if 语句,它们一定在 else 语句之前。

一旦else if 匹配成功,剩余的 else if 是或 else 将不会被测试(执行)。

语法

创建 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"

数据分析咨询请扫描二维码

客服在线
立即咨询