📜  R If else语句

📅  最后修改于: 2021-01-08 09:30:32             🧑  作者: Mango

If-else语句

在if语句中,当条件为true时,将执行内部代码。如果条件为假,则将执行if块之外的代码。

还有另一种决策语句,称为if-else语句。 if-else语句是if语句,后跟else语句。当布尔表达式为false时,将执行if-else语句else语句。简而言之,如果布尔表达式的值为真,则执行if块,否则执行else块。

R编程将任何非零和非空值都视为true,如果该值是零或null,则将它们视为false。

If-else语句的基本语法如下:

if(boolean_expression) {
   // statement(s) will be executed if the boolean expression is true.
} else {
   // statement(s) will be executed if the boolean expression is false.
}

流程图

例子1

# local variable definition
a<- 100
#checking boolean condition
if(a<20){
    # if the condition is true then print the following
    cat("a is less than 20\n")
}else{
    # if the condition is false then print the following
    cat("a is not less than 20\n")
}
cat("The value of a is", a)

输出:

例子2

x <- c("Hardwork","is","the","key","of","success")

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

输出:

例子3

a<- 100
#checking boolean condition
if(a<20){
    cat("a is less than 20")
    if(a%%2==0){
        cat(" and an even number\n")
    }
    else{
        cat(" but not an even number\n")
    }
}else{
    cat("a is greater than 20")
    if(a%%2==0){
        cat(" and an even number\n")
    }
    else{
        cat(" but not an even number\n")
    }
}

输出:

例子4

a<- 'u'
if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){
    cat("character is a vowel\n")    
}else{
    cat("character is a constant")
}
cat("character is =",a)
}

输出:

例子5

a<- 'u'
if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){
    cat("character is a vowel\n")    
}else{
    cat("character is a constant")
}
cat("character is =",a)
}

输出: