R If-else 语句

R If-else 语句 首页 / R入门教程 / R If-else 语句

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

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

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

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

链接:https://www.learnfk.comhttps://www.learnfk.com/R/r-if-else-statement.html

来源:LearnFk无涯教程网

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.
}

流程图

R If-else statement

例子1

# 定义本地变量
a<- 100  
#检查条件语句 
if(a<20){  
    # 如果条件为True,则执行这里 
    cat("a is less than 20\n")  
}else{  
    # 如果条件为False,则执行这里
    cat("a is not less than 20\n")  
}  
cat("The value of a is", a)  

输出:

R If-else statement

例子2

x <- c("Learnfk","is","the","key","of","success")  
  
if("key" %in% x) {    
   print("key is found")  
} else {  
   print("key is not found")  
}  

输出:

R If-else statement

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

输出:

R If-else statement

例子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)  

输出:

R If-else statement

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

微服务架构核心20讲 -〔杨波〕

微服务架构实战160讲 -〔杨波〕

深入拆解Tomcat & Jetty -〔李号双〕

Linux实战技能100讲 -〔尹会生〕

Netty源码剖析与实战 -〔傅健〕

数据分析思维课 -〔郭炜〕

AI绘画核心技术与实战 -〔南柯〕

结构沟通力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)