R語言 If...Else語句

2018-12-19 15:21 更新

if語句后面可以是一個可選的else語句,當(dāng)布爾表達(dá)式為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.
}

如果布爾表達(dá)式的計(jì)算結(jié)果為真,則將執(zhí)行if代碼塊,否則將執(zhí)行代碼塊。

流程圖


x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}

當(dāng)上面的代碼被編譯和執(zhí)行時,它產(chǎn)生以下結(jié)果 -
[1] "Truth is not found"
這里“Truth”和“truth”是兩個不同的字符串。

if ... else if ... else語句

if語句后面可以跟一個可選的else if ... else語句,這對于使用single if ... else if語句測試各種條件非常有用。

當(dāng)使用if,else if,else語句有幾點(diǎn)要記住。

  • 如果可以有零或一個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")
}
當(dāng)上面的代碼被編譯和執(zhí)行時,它產(chǎn)生以下結(jié)果 -

[1] "truth is found the second time"









以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號