R else if 语句

R else if 语句 首页 / R入门教程 / R else if 语句

此语句也称为嵌套if-else语句。 if语句后面是可选的else if ..... else语句。该语句用于在单个if ...... else if语句中测试各种条件。当我们使用if .... else if ..... else语句时,需要牢记一些关键点。这些要点如下:

  1. if 语句可以包含零个或一个 else 语句,并且必须在任何 else if的语句之后。
  2. if 语句可以有许多 else if 语句,它们位于else语句之前。
  3. 一旦 else if 语句成功,将不会测试其余的 else if else

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

if(boolean_expression 1) {
  //This block executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
  //This block executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
  //This block executes when the boolean expression 3 is true.
} else {
  //This block executes when none of the above condition is true. 
}

流程图

R else if statement

例子1

age <- readline(prompt="Enter age: ")  
age <- as.integer(age)  
if(age<18)  
    print("You are child")  
else if(age>30)  
    print("You are old guy")  
else  
    print("You are adult")  

输出:

R else if statement

例子2

marks=83;
if(marks>75){
	print("First class")
}else if(marks>65){
	print("Second class")
}else if(marks>55){
	print("Third class")
}else{
	print("Fail")
}

输出:

R else if statement

例子3

cat("1) For Addition\n")  
cat("2) For Subtraction\n")  
cat("3) For Division\n")  
cat("4) For multiplication\n")  
n1<-readline(prompt="Enter first number:")  
n2<-readline(prompt="Enter second number:")  
choice<-readline(prompt="Enter your choice:")  
n1<- as.integer(n1)  
n2<- as.integer(n2)  
choice<- as.integer(choice)  
if(choice==1){  
    sum <-(n1+n2)  
    cat("sum=",sum)  
}else if(choice==2){  
    sub<-(n1-n2)  
    cat("sub=",sub)  
}else if(choice==3){  
    div<-n1/n2  
    cat("Division=",div)  
}else if(choice==4){  
    mul<-n1*n2  
    cat("mul=",mul)  
}else{  
    cat("wrong choice")  
}  

输出:

R else if statement

例子4

x <- c("Learnfk","is","the","key","of","success")  
if("Success" %in% x) {  
   print("success is found in the first time")  
} else if ("success" %in% x) {  
   print("success is found in the second time")  
} else {  
   print("No success found")  
}  

输出:

R else if statement

例子5

n1=4
n2=87
n3=43
n4=74
if(n1>n2){
	if(n1>n3&&n1>n4){
		largest=n1
	}
}else if(n2>n3){
	if(n2>n1&&n2>n4){
		largest=n2
	}
}else if(n3>n4){
	if(n3>n1&&n3>n2){
		largest=n3
	}
}else{
	largest=n4
}
cat("THE LEARNFK.COM Largest number is =",largest)

输出:

R else if statement

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

技术教程推荐

零基础学Python -〔尹会生〕

Go语言从入门到实战 -〔蔡超〕

SQL必知必会 -〔陈旸〕

黄勇的OKR实战笔记 -〔黄勇〕

Spark核心原理与实战 -〔王磊〕

实用密码学 -〔范学雷〕

打造爆款短视频 -〔周维〕

说透低代码 -〔陈旭〕

手把手带你搭建推荐系统 -〔黄鸿波〕

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