R语言 决策–if、if-else、if-else-if梯子、嵌套if-else和switch
决策是关于根据某些条件来决定语句的执行顺序。在决策中,程序员需要提供一些由程序评估的条件,同时还提供一些如果条件为真则执行的语句,如果条件被评估为假则可选其他语句。
R语言中的决策语句如下。
- if 语句
- if-else 语句
- if-else-if 梯子
- 嵌套的if-else语句
- switch语句
if语句
关键字 if 告诉编译器这是一条决策控制指令,关键字if后面的条件总是包含在一对小括号中。如果条件为 “true”,语句就会被执行;如果条件为 “false”,语句就不会被执行。
语法
if(condition is true){
执行该语句
}
流程图
例子
# R program to illustrate
# if statement
a <- 76
b <- 67
# TRUE condition
if(a > b)
{
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is : ", c))
}
# FALSE condition
if(a < b)
{
c <- a - b
print("condition a < b is TRUE")
print(paste("Difference between a, b is : ", c))
}
输出
[1] "condition a > b is TRUE"
[1] "Difference between a, b is : 9"
if-else 语句
If-else ,为我们提供了一个可选的else块,如果if块的条件为false,它将被执行。如果提供给if块的条件是真的,那么if块中的语句将被执行,否则else块中的语句将被执行。
语法
if(condition is true) {
执行该语句
} else {
执行此语句
}
流程图
例子 :
# R if-else statement Example
a <- 67
b <- 76
# This example will execute else block
if(a > b)
{
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is : ", c))
} else
{
c <- a - b
print("condition a > b is FALSE")
print(paste("Difference between a, b is : ", c))
}
输出
[1] "condition a > b is FALSE"
[1] "Difference between a, b is : -9"
if-else-if 梯子
它类似于if-else语句,这里唯一的区别是if语句与else相连。如果提供给if块的条件是真实的,那么if块中的语句就会被执行,如果提供的另一个条件被检查,如果是真实的,那么该块中的语句就会被执行。
语法
if(condition 1 is true) {
执行该语句
} else if(condition 2 is true) {
执行此语句
} else {
执行此语句
}
流程图
例子 :
# R if-else-if ladder Example
a <- 67
b <- 76
c <- 99
if(a > b && b > c)
{
print("condition a > b > c is TRUE")
} else if(a < b && b > c)
{
print("condition a < b > c is TRUE")
} else if(a < b && b < c)
{
print("condition a < b < c is TRUE")
}
输出
[1] "condition a < b < c is TRUE"
嵌套的if-else语句
当我们有一个if-else块作为if块中的一个语句,或者可以选择在else块中,那么它就被称为嵌套的if else语句。当一个if条件为真时,下面的子if条件将被验证,如果条件错误,则执行else语句,这发生在父if条件中。如果父级if条件为假,则执行else块,也可能包含子级if else语句。
语法
if(parent condition is true) {
if( child condition 1 is true) {
execute this statement
} else {
execute this statement
}
} else {
if(child condition 2 is true) {
execute this statement
} else {
execute this statement
}
}
流程图
例子
# R Nested if else statement Example
a <- 10
b <- 11
if(a == 10)
{
if(b == 10)
{
print("a:10 b:10")
} else
{
print("a:10 b:11")
}
} else
{
if(a == 11)
{
print("a:11 b:10")
} else
{
print("a:11 b:11")
}
}
输出
[1] "a:10 b:11"
Switch语句
在这个switch函数中,表达式被匹配到案例列表中。如果找到了匹配,那么它就打印出该案例的值。这里没有默认的案例。如果没有匹配的情况,则输出NULL,如示例所示。
语法
switch (expression, case1, case2, case3,..., case n )
流程图:
例子
# R switch statement example
# Expression in terms of the index value
x <- switch(
2, # Expression
"Geeks1", # case 1
"for", # case 2
"Geeks2" # case 3
)
print(x)
# Expression in terms of the string value
y <- switch(
"GfG3", # Expression
"GfG0"="Geeks1", # case 1
"GfG1"="for", # case 2
"GfG3"="Geeks2" # case 3
)
print(y)
z <- switch(
"GfG", # Expression
"GfG0"="Geeks1", # case 1
"GfG1"="for", # case 2
"GfG3"="Geeks2" # case 3
)
print(z)
print(z)
输出
[1] "for"
[1] "Geeks2"
NULL