if語句后面可以是一個可選的else語句,當布爾表達式為false時執(zhí)行。 語法在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.
}
如果布爾表達式的計算結果為真,則將執(zhí)行if代碼塊,否則將執(zhí)行代碼塊。
流程圖
例x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
當上面的代碼被編譯和執(zhí)行時,它產生以下結果 -[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中創(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")
}
當上面的代碼被編譯和執(zhí)行時,它產生以下結果 -
[1] "truth is found the second time"
|