打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
R语言 If...Else语句

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"

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Perl IF…ELSE 语句 | 菜鸟教程
TypeScript 条件语句 | 菜鸟教程
让人想骂街的 Python 炫技操作:条件语句的七种写法
Python 炫技操作:条件语句的七种写法
PHP中if语句5种写法
===从零基础开始,到精通插件===-#4
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服