分支语句"/>
R语言 编写条件分支语句
条件分支语句在编程语言中非常常见。R语言中,常用的条件分支语句包括if…else语句和switch语句。
if-else结构
在R语言中创建if-else语句的基本语法如下所示:
if (boolean expression) {
// statement(s) will execute if the boolean expression is true.
} else {
// statement(s) will execute if the boolean expression is false.
}
该语句可以实现多重条件的嵌套,三重嵌套的条件语句的基本语法如下所示:
if (boolean_expression 1) {
// statement(s) will execute if the boolean_expression 1 is true.
} else if (boolean_expression 2) {
// statement(s) will execute if the boolean_expression 2 is true.
} else if (boolean_expression 3) {
// statement(s) will execute if the boolean_expression 3 is true.
} else {
// executes when none of the above condition is true.
}
ifelse结构
ifelse结构是if-else结构比较紧凑的向量化版本,其语法如下:
ifelse(condition, statement1, statement2)
若condition为TRUE,则执行第一个语句;
若condition为FALSE,则执行第二个语句
使用switch分支语句
switch分支语句的使用格式如下:
switch(expression,list)
- 其中,expression为表达式,list为列表,可以用有名定义
- 如果表达式返回值在1到length(list)之间,则返回列表相应位置的值,否则返回“NULL”值。
当list是有名定义,表达式等于变量名时,返回变量名对应的值,否则返回“NULL”值
更多推荐
R语言 编写条件分支语句
发布评论