R - if...else 語句



一個if語句後面可以跟著一個可選的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 語句測試各種條件非常有用。

使用ifelse ifelse語句時,需要注意以下幾點。

  • 一個if可以有零個或一個else,並且它必須位於任何else if之後。

  • 一個if可以有零個到多個else if,並且它們必須位於else之前。

  • 一旦else if成功,就不會測試任何剩餘的else ifelse

語法

在 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"
r_decision_making.htm
廣告

© . All rights reserved.