在任何一種編程語言中都有if語句,在生物信息學(xué)分析中,經(jīng)常會篩選滿足一定條件的數(shù)據(jù),if語句就很有用段标。在R語言中創(chuàng)建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),那么將執(zhí)行if語句中的代碼塊炉奴,否則將執(zhí)行else語句中的代碼塊逼庞。
x <- c("Bio","Info","Cloud","BioInfoCloud")
if("BioInfoCloud" %in% x) {
print("BioInfoCloud is found")
} else {
print("BioInfoCloud is not found")
}
當上述代碼被編譯和執(zhí)行時,它產(chǎn)生以下結(jié)果:
[1] "BioInfoCloud is found"
Else不是必須的瞻赶,如果只需要在某條件成立時執(zhí)行某個任務(wù)赛糟,那么只要使用if語句就可以了。如果條件不止一個/不止兩個的時候砸逊,可以添加一個/多個 else if語句璧南,但最后必須以else結(jié)尾。
一個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中創(chuàng)建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")
}
代碼運行得到下面結(jié)果:
[1] "truth is found the second time"