一個if
語句可以跟隨一個可選的else
語句,當布爾運算式為false
時執行else
語句中的語句塊代碼。
語法
在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
語句中的代碼塊。
if...else
語句的流程圖如下 -
示例
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
語句,這對使用單個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"