與其它高級語言類似,R中也有自己的控制結構,主要包括分支結構和循環結構。靈活使用R的控制結構可以幫助我們處理更加復雜的數據分析任務。
本文首先探討R中分支結構的if...else結構。
if/else分支結構主要用于兩種分支情況下,主要使用格式有三種情況:
(1)只有一個if的結構
if(cond) {expr}
即當括弧中的cond條件為TRUE時,則執行表達式expr,否則跳過后執行其后的語句。
(2)if...else結構
if(cond) {cons.expr} else {alt.expr}
即條件cond為TRUE時,則執行表達式cons.expr,否則執行alt.expr
(3)if的嵌套使用
常見形式如下:
if(cond_1)
{expr_1}
else if(cond_2)
{expr_2}
else if(cond_3)
{expr_3} else {expr_4}
注意:在上面的三種情況下,如果表達式只有一個時,可以省略大括號{};
同時,else部分不能單獨在一行,即在else同一行中,else前面應有內容。除非,if...else放在大括號中。
下面是幾個例子:
(1)單個if
num <- 6
if(num%%2==0)
print("是偶數")
print("Hello,VeVb.com")
本例子中,%%為求余數運算符,如果num能被2整除余數為0,則輸出是偶數,同時不管if的條件是否滿足,Hello,VeVb.com的內容都會被輸出來。
運行效果如下圖所示
(2)if...else
num<-6
if(num%%2==0)
print("是偶數") else print("是奇數") #else不能單獨一行,否則報錯:意外的'else' in "else"
print("Hello,VeVb.com")
下圖給出了num為5,num為6,else單獨一行時,if...else放在大括號中時的4中情況下的輸出情況:
(3)if/else的嵌套情況
score <- 89
if( score>=0 && score<60)
print("不及格") else if(score < 70)
print("及格") else if(score < 80)
print("中等") else if(score < 90)
print("良好") else if(score <= 100)
print("優秀") else
print("成績不合理")
若將以上內容放在大括號中,會更加直觀一些,如下:
score <- 89
{
if( score>=0 && score<60)
print("不及格")
else if(score < 70)
print("及格")
else if(score < 80)
print("中等")
else if(score < 90)
print("良好")
else if(score <= 100)
print("優秀")
else
print("成績不合理")
}
本文(完)
新聞熱點
疑難解答