# R 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 {
}``````

### 例子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)
}``````

• 回顶