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

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

技术教程推荐

趣谈网络协议 -〔刘超〕

如何做好一场技术演讲 -〔极客时间〕

Linux性能优化实战 -〔倪朋飞〕

现代C++编程实战 -〔吴咏炜〕

恋爱必修课 -〔李一帆〕

人人都用得上的数字化思维课 -〔付晓岩〕

快手 · 音视频技术入门课 -〔刘歧〕

现代React Web开发实战 -〔宋一玮〕

AI 应用实战课 -〔黄佳〕

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