R If 语句

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

if语句由布尔表达式组成,后跟一个或多个语句。 if语句是最简单的决策语句,可帮助我们根据条件做出决定。

仅当布尔表达式的值为真时,才会执行if语句中的代码块。如果该语句的计算结果为false,则该条件后面提到的代码将运行。

R中if语句的语法如下:

if(boolean_expression) {
  //If the boolean expression is true, then statement(s) will be executed. 
}

流程图

R If Statement

让我们看一些示例,以了解语句如何工作以及如何在R中执行特定任务。

例子1

x <-24L  
y <- "learnfk"  
if(is.integer(x))  
{  
    print("x is an Integer")  
}  

输出:

R If Statement

例子2

x <-20  
y<-24  
count=0  
if(x<y)  
{  
    cat(x,"is a smaller number\n")  
    count=1  
}  
if(count==1){  
    cat("LEARNFK is successfully execute")  
}  

输出:

R If Statement

例子3

x <-1  
y<-24  
count=0  
while(x<y){  
    cat(x,"is a smaller number\n")  
    x=x+2  
    if(x==15)  
        break  
}  

输出:

R If Statement

例子4

x <-24  
if(x%%2==0){  
    cat(x," is an even number")  
}  
if(x%%2!=0){  
    cat(x," is an odd number")  
}  

输出:

R If Statement

例子5

year1 = 2021
if(year1 %% 4 == 0) {
 if(year1 %% 100 == 0) { 
	 if(year1 %% 400 == 0) { 
		 cat(year1,"is a leap year") 
		} else {
		 cat(year1,"is not a leap year") 
		}
	} else {
	 cat(year1,"is a leap year") 
	}
} else {
 cat(year1,"is not a leap year") 
}

输出:

R If Statement

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

技术教程推荐

数据结构与算法之美 -〔王争〕

Android开发高手课 -〔张绍文〕

重学前端 -〔程劭非(winter)〕

检索技术核心20讲 -〔陈东〕

Redis核心技术与实战 -〔蒋德钧〕

恋爱必修课 -〔李一帆〕

性能优化高手课 -〔尉刚强〕

PyTorch深度学习实战 -〔方远〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

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