在if语句中,当条件为true时,将执行内部代码。如果条件为false,则将执行if块之外的代码。
还有另一种决策语句,称为if-else语句。 if-else语句是if语句,后跟else语句。当布尔表达式为false时,将执行if-else语句else语句。简而言之,如果布尔表达式的值为真,则执行if块,否则执行else块。
R编程将任何非零和非空值都视为true,并且如果该值是零或null,则将它们视为false。
If-else语句的基本语法如下:
链接:https://www.learnfk.comhttps://www.learnfk.com/R/r-if-else-statement.html
来源:LearnFk无涯教程网
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. }
流程图
# 定义本地变量 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)
输出:
x <- c("Learnfk","is","the","key","of","success")
if("key" %in% x) {
print("key is found")
} else {
print("key is not found")
}
输出:
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")
}
}
输出:
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)
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)