条件语句

Reads: 987 Edit

1 if-else语句

if (条件){
   表达式1
   }else{
   表达式2
}

说明:若逻辑判断值为TRUE,则执行{expr1};否则不执行{expr}。需要注意的是,else不能单独成一行,它的前边必须有内容,如“}”

采用if-else语句计算变量的绝对值

计算-2的绝对值:

x=-2
if(x>=0){
  x
}else{
  -x
}
[1] 2  

计算5的绝对值:

x=5
if(x>=0){
  x
}else{
  -x
}
[1] 5

2 ifelse语句

ifelse(条件,表达式1,表达式2)	

说明:ifelse语句是if-else语句的简化版本。如果条件为真,则输出表达式1;否则输出表达式2。

采用ifelse语句计算变量的绝对值

计算-2的绝对值:

x=-2
ifelse(x>=0,x,-x)	
[1] 2

计算5的绝对值:

x=5
ifelse(x>=0,x,-x)	
[1] 5

3 if-"else if"-else语句

if (条件1){
  表达式1
}else if(条件2){
  表达式2
}else if(条件3){
  表达式3
}
...
else if(条件n){
  表达式n
}else{
  表达式n+1
}

采用if-"else if"-else语句判断成绩

判断87分对应的成绩等级:

score=87
if (score>=90){
  print("优秀")
}else if(score>=80 & score<90){
  print("良好")
}else if(score>=60 & score<80){
  print("合格")
}else{
  print("不合格")
}
[1] "良好"

Comments

Make a comment