R语言 If…Else语句
一个 if 语句后面可以跟着一个可选的 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. }
如果Boolean表达式为真,则执行代码中的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 语句可以有零个到多个 else if ,并且它们必须放在else之前。
-
一旦一个 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"
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com