在任何一种编程语言中都有if语句,在生物信息学分析中,经常会筛选满足一定条件的数据,if语句就很有用。在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.
}
图片
如果布尔表达式求值为真(true),那么将执行if语句中的代码块,否则将执行else语句中的代码块。
x <- c("Bio","Info","Cloud","BioInfoCloud")
if("BioInfoCloud" %in% x) {
print("BioInfoCloud is found")
} else {
print("BioInfoCloud is not found")
}
当上述代码被编译和执行时,它产生以下结果:
[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语句的基本语法是
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"
网友评论