×

R 教程

R语言 概述R语言 环境设置R语言 基本语法R语言 数据类型R语言 变量R语言 运算符R语言 决策R语言 包R语言 循环R语言 数据重塑R语言 函数R语言 字符串R语言 向量R语言 列表R语言 矩阵R语言 数组R语言 因子R语言 数据帧

R语言 图表

R语言 条形图R语言 箱线图R语言 直方图R语言 折线图R语言 散点图R语言 饼状图

R语言 数据接口

R语言 CSV文件R语言 Excel文件R语言 二进制文件R语言 XML文件R语言 JSON文件R语言 Web数据R语言 数据库

R语言 统计示例

R语言 平均值,中位数和模式R语言 线性回归R语言 多重回归R语言 逻辑回归R语言 标准分布R语言 二项分布R语言 泊松回归R语言 协方差分析R语言 时间序列分析R语言 非线性最小二乘R语言 决策树R语言 随机森林算法R语言 生存分析R语言 卡方检验

R语言 相关资源

R语言 外部资源R语言 相关讨论R语言 面试题

R语言 If...Else语句


R语言 决策R语言 决策


if语句后面可以是一个可选的else语句,当布尔表达式为false时执行。

语法

在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代码块,否则将执行代码块。

流程图


x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}

当上面的代码被编译和执行时,它产生以下结果 -
[1] "Truth is not found"
这里“Truth”和“truth”是两个不同的字符串。

if ... else if ... else语句

if语句后面可以跟一个可选的else if ... else语句,这对于使用single if ... else if语句测试各种条件非常有用。

当使用if,else if,else语句有几点要记住。

  • 如果可以有零或一个else,它必须在任何其他if之后。
  • 一个if可以有0到许多else if和它们必须在else之前。
  • 一旦一个else如果成功,没有任何剩余的else if或else将被测试。

语法

在R中创建if ... else if ... else语句的基本语法是 -

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

x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found the first time")
} else if ("truth" %in% x) {
   print("truth is found the second time")
} else {
   print("No truth found")
}
当上面的代码被编译和执行时,它产生以下结果 -

[1] "truth is found the second time"


R语言 决策R语言 决策


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)