前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言基础教程——第四章:if语句

R语言基础教程——第四章:if语句

作者头像
DoubleHelix
发布2019-08-07 08:25:12
1.3K0
发布2019-08-07 08:25:12
举报
文章被收录于专栏:生物信息云生物信息云

在任何一种编程语言中都有if语句,在生物信息学分析中,经常会筛选满足一定条件的数据,if语句就很有用。在R语言中创建if..else语句的基本语法是 :

代码语言:javascript
复制
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语句中的代码块。

代码语言:javascript
复制
x <- c("Bio","Info","Cloud","BioInfoCloud")if("BioInfoCloud" %in% x) {   print("BioInfoCloud is found")} else {   print("BioInfoCloud is not found")}

‍当上述代码被编译和执行时,它产生以下结果:

代码语言:javascript
复制
[1] "BioInfoCloud is found"

Else不是必须的,如果只需要在某条件成立时执行某个任务,那么只要使用if语句就可以了。如果条件不止一个/不止两个的时候,可以添加一个/多个 else if语句,但最后必须以else结尾。

一个if语句可以跟随一个可选的else if...else语句,这对使用单个if...else else语句来测试各种条件非常有用。

当使用if,else if, else语句时要注意几点。

if语句可以有零个或一个else,但如果有else if语句,那么else语句必须在else if语句之后。if语句可以有零或多else if语句,else if语句必须放在else语句之前。当有一个else if条件测试成功,其余的else...if或else将不会被测试。

语法

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

代码语言:javascript
复制
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.}

给一个案例:

代码语言:javascript
复制
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")}

代码运行得到下面结果:

代码语言:javascript
复制
[1] "truth is found the second time"
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 MedBioInfoCloud 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档