R语言 if-else 语句

R语言 if-else 语句

编程语言中的if语句只告诉我们,如果一个条件为真,它将执行一个语句块,如果条件为假,则不执行。但是,如果我们想在条件为假的情况下做其他事情,该怎么办呢?这时就需要R else语句。 我们可以将else语句与if语句一起使用,在条件为假时执行一个代码块。

R语言 if-else语句的语法

if (condition)
{
    // Executes this block if
    // condition is true
} else
{
    // Executes this block if
    // condition is false
}
R

R - if-else 语句

R编程中if-else语句的工作原理

  • 控制落入if块。
  • 流程跳转到Condition。
  • 对Condition进行测试。
    • 如果Condition为真,转到第4步。
    • 如果Condition为假,转到第5步。
  • 执行if块或if中的主体。
  • 执行else块或else块中的主体。
  • 流程退出if-else块。

R语言 if-else语句的流程图

R - if-else 语句

R语言 if-else 语句示例

例1 :

x <- 5
  
# Check value is less than or greater than 10
if(x > 10)
{
    print(paste(x, "is greater than 10"))
} else
{
    print(paste(x, "is less than 10"))
}
R

输出

[1] "5 is less than 10"
R

在上述代码中,首先,x被初始化为5,然后检查if条件(x>10),结果为false。流进入else块,并打印出 “5小于10 “的语句。

例2 :

x <- 5
 
# Check if value is equal to 10
if(x == 10)
{
    print(paste(x, "is equal to 10"))
} else
{
    print(paste(x, "is not equal to 10"))
}
R

输出

[1] "5 is not equal to 10" 
R

R中的嵌套if-else语句

if-else语句可以嵌套在一起,形成一组语句,并根据条件逐一评估表达式,分别从外部条件开始到内部逐一评估。一个if-else语句在另一个if-else语句中,能更好地证明其定义。

语法

if(condition1){
# execute only if condition 1 satisfies
if(condition 2){ 
# execute if both condition 1 and 2 satisfy
}
}else{
}
R

例子

# creating values
var1 <- 6
var2 <- 5
var3 <- -4
 
# checking if-else if ladder
if(var1 > 10 || var2 < 5){
print("condition1")
}else{
if(var1 <4 ){
    print("condition2")
}else{
    if(var2>10){
    print("condition3")
    }
    else{
    print("condition4")
    }
}
}
R

输出

[1] "condition4"
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册