R If-else 语句

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

在if语句中,当条件为true时,将执行内部代码。如果条件为false,则将执行if块之外的代码。

还有另一种决策语句,称为if-else语句。 if-else语句是if语句,后跟else语句。当布尔表达式为false时,将执行if-else语句else语句。简而言之,如果布尔表达式的值为真,则执行if块,否则执行else块。

R编程将任何非零和非空值都视为true,并且如果该值是零或null,则将它们视为false。

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

无涯教程网

if(boolean_expression) {
  //statement(s) will be executed if the boolean expression is true.
} else {
  //statement(s) will be executed if the boolean expression is false.
}

流程图

R If-else statement

例子1

# 定义本地变量
a<- 100  
#检查条件语句 
if(a<20){  
    # 如果条件为True,则执行这里 
    cat("a is less than 20\n")  
}else{  
    # 如果条件为False,则执行这里
    cat("a is not less than 20\n")  
}  
cat("The value of a is", a)  

输出:

R If-else statement

例子2

x <- c("Learnfk","is","the","key","of","success")  
  
if("key" %in% x) {    
   print("key is found")  
} else {  
   print("key is not found")  
}  

输出:

R If-else statement

例子3

a<- 100  
#checking boolean condition  
if(a<20){  
    cat("a is less than 20")  
    if(a%%2==0){  
        cat(" and an even number\n")  
    }  
    else{  
        cat(" but not an even number\n")  
    }  
}else{  
    cat("a is greater than 20")  
    if(a%%2==0){  
        cat(" and an even number\n")  
    }  
    else{  
        cat(" but not an even number\n")  
    }  
}  

输出:

R If-else statement

例子4

a<- 'u'  
if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U'){  
    cat("character is a vowel\n")     
}else{  
    cat("character is a constant")  
}  
cat("character is =",a)  

输出:

R If-else statement

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

技术教程推荐

技术领导力实战笔记 -〔TGO鲲鹏会〕

机器学习40讲 -〔王天一〕

MySQL实战45讲 -〔林晓斌〕

10x程序员工作法 -〔郑晔〕

DevOps实战笔记 -〔石雪峰〕

MongoDB高手课 -〔唐建法(TJ)〕

乔新亮的CTO成长复盘 -〔乔新亮〕

A/B测试从0到1 -〔张博伟〕

手把手带你写一个MiniSpring -〔郭屹〕

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