if语句由布尔表达式组成,后跟一个或多个语句。 if语句是最简单的决策语句,可帮助我们根据条件做出决定。
仅当布尔表达式的值为真时,才会执行if语句中的代码块。如果该语句的计算结果为false,则该条件后面提到的代码将运行。
R中if语句的语法如下:
if(boolean_expression) { //If the boolean expression is true, then statement(s) will be executed. }
流程图
让我们看一些示例,以了解语句如何工作以及如何在R中执行特定任务。
x <-24L
y <- "learnfk"
if(is.integer(x))
{
print("x is an Integer")
}
输出:
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")
}
输出:
x <-1
y<-24
count=0
while(x<y){
cat(x,"is a smaller number\n")
x=x+2
if(x==15)
break
}
输出:
x <-24
if(x%%2==0){
cat(x," is an even number")
}
if(x%%2!=0){
cat(x," is an odd number")
}
输出:
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") }
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)