课程表

R语言 基础教程

R语言 图表

R语言 数据接口

R语言 统计示例

工具箱
速查手册

R语言 If...Else语句

当前位置:免费教程 » 程序设计 » R语言

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

语法

在R中创建if ... else语句的基本语法是 -

  1. if(boolean_expression) {
  2. // statement(s) will execute if the boolean expression is true.
  3. } else {
  4. // statement(s) will execute if the boolean expression is false.
  5. }

如果布尔表达式的计算结果为真,则将执行if代码块,否则将执行代码块。

流程图


  1. x <- c("what","is","truth")
  2. if("Truth" %in% x) {
  3. print("Truth is found")
  4. } else {
  5. print("Truth is not found")
  6. }

当上面的代码被编译和执行时,它产生以下结果 -
  1. [1] "Truth is not found"

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


if ... else if ... else语句

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

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

  • 如果可以有零或一个else,它必须在任何其他if之后。
  • 一个if可以有0到许多else if和它们必须在else之前。
  • 一旦一个else如果成功,没有任何剩余的else if或else将被测试。

语法

在R中创建if ... else if ... else语句的基本语法是 -

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

  1. x <- c("what","is","truth")
  2. if("Truth" %in% x) {
  3. print("Truth is found the first time")
  4. } else if ("truth" %in% x) {
  5. print("truth is found the second time")
  6. } else {
  7. print("No truth found")
  8. }
当上面的代码被编译和执行时,它产生以下结果 -

  1. [1] "truth is found the second time"

尝试一下

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号