位置:首頁 > 大數據教學 > R語言教學 > R語言if...else語句

R語言if...else語句

if語句可以跟著可選的 else語句,當 if語句布爾表達式是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 代碼塊將被執行。

流程圖

R if...else statement

示例

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 if 語句來測試各種條件非常有用的。

當使用 if , else if , else 語句有幾點要牢記。

  • if 語句後可以有零或一個 else 語句,它必須出現在 else if語句之後。

  • 一個 if 語句 可有0到多個 else if 語句,它們一定在 else 語句之前。

  • 一旦else if 匹配成功,剩餘的 else if 是或 else 將不會被測試(執行)。

語法

創建 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"