分享

R语言 If...Else语句

 imtravelinghah 2022-07-16 发布于广西

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

语法

在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.
}
如果布尔表达式的计算结果为真,则将执行if代码块,否则将执行代码块。

流程图


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语句,这对于使用single if ... else if语句测试各种条件非常有用。

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

  • 如果可以有零或一个else,它必须在任何其他if之后。
  • 一个if可以有0到许多else if和它们必须在else之前。
  • 一旦一个else如果成功,没有任何剩余的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"

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多