蓝色天空.知识 · 实践 · 创造
我的收藏
R 教程目录 29章
R / LEARN BY DOING

R 判断语句与 switch 分派

区分单条件、互斥判断链与按数字或名称选择的 switch。

学完这一章,你能够

  • 区分单条件、互斥判断链与按数字或名称选择的 switch。

先检查一个明确条件

if 接受一个可转为逻辑值的单元素条件,且条件不能缺失。NA、空向量和长度大于一的向量都会报错。字面值 24L 是整数,24 默认是 double,所以 is.integer() 对它们给出的结果不同。

条件为真时执行块内语句。条件为假且没有 else 时,if 返回不可见的 NULL。编写示例说明用 # 注释,R 不识别 // 作为行注释。

从上往下选择分支

if 和 else 根据一项条件走不同路径。%in% 可以先检查一个传感器名称是否在已安装列表中,再显示可用或缺失。

if、else if 与 else 组成互斥判断链。本站示例先看读数是否至少为 18,再看是否至少为 12,其余走 low。19 得 high,14 得 medium,11 得 low。

先判断是否至少 18,再判断是否至少 12,分别返回 high、medium、low
本站流程图对应实际运行的三种读数。

switch 的数字与名称规则

数字形式先把选择值转成整数,再从 1 起数备选项。2.9 转成 2。越界时返回不可见的 NULL。选择表达式可以在运行时计算。

字符形式按名称精确匹配。没有完全匹配且没有未命名备选项时返回 NULL。一个未命名备选项可以处理无匹配的情况,多个未命名项在没有匹配时会报错。

遇到重复名称时使用首个匹配项。字符形式的匹配项若有名称但没有表达式,会继续到后面的非空备选项。普通选择只求值选中的分支,因此未选的 stop() 不会运行。

运行判断链、边界与 switch

含完整源码 · 57 行
展开查看收起
r
emit <- function(key, values) {
  cat(key, "=", paste(values, collapse = ","), "\n", sep = "")
}
classify <- function(count) {
  if (count >= 18) {
    "high"
  } else if (count >= 12) {
    "medium"
  } else {
    "low"
  }
}
emit("integer", c(is.integer(24L), is.integer(24)))
installed <- c("wind", "rain")
emit("membership", c(if ("rain" %in% installed) "available" else "missing",
                     if ("heat" %in% installed) "available" else "missing"))
emit("chain", c(classify(19), classify(14), classify(11)))
skipped <- withVisible(if (FALSE) 1L)
emit("no_else", c(is.null(skipped$value), skipped$visible))
error_from <- function(expr) tryCatch({force(expr); FALSE}, error = function(e) TRUE)
emit("conditions", c(error_from(if (NA) 1L), error_from(if (logical()) 1L),
                     error_from(if (c(TRUE, FALSE)) 1L),
                     error_from(parse(text = "if (TRUE) { // invalid }"))))

emit("numeric_switch", c(switch(3, "north", "east", "south"),
                         switch(2.9, "north", "east", "south"),
                         is.null(switch(4, "north", "east", "south"))))
emit("named_switch", c(switch("east", east = "station-2", west = "station-1"),
                       is.null(switch("ea", east = "station-2")),
                       switch("other", east = "station-2", "unassigned")))
emit("switch_rules", c(switch("a", a = "first", a = "second"),
                       switch("spring", spring =, summer = "wet"),
                       switch("ok", ok = "safe", stop("unselected")),
                       error_from(switch("unknown", "first", "second"))))

png("decision-flow.png", width = 720, height = 420)
par(mar = c(1, 1, 2.4, 1))
plot.new()
plot.window(xlim = c(0, 10), ylim = c(0, 7))
title("Decision order for one observation count", col.main = "#17354b")
node <- function(x, y, text_value, fill) {
  rect(x - 1.45, y - 0.42, x + 1.45, y + 0.42, col = fill, border = "#315770")
  text(x, y, text_value, col = "#17354b", cex = 1.1)
}
node(3, 6, "count >= 18?", "#e1eef6")
node(7, 6, "high (19)", "#dff0da")
node(3, 3.8, "count >= 12?", "#e1eef6")
node(7, 3.8, "medium (14)", "#dff0da")
node(3, 1.6, "low (11)", "#dff0da")
arrows(4.45, 6, 5.55, 6, length = 0.08)
arrows(4.45, 3.8, 5.55, 3.8, length = 0.08)
arrows(3, 5.58, 3, 4.22, length = 0.08)
arrows(3, 3.38, 3, 2.02, length = 0.08)
text(c(5, 5), c(6.32, 4.12), "yes", cex = 0.92)
text(c(3.37, 3.37), c(4.96, 2.76), "no", cex = 0.92)
invisible(dev.off())
三段判断依次给 high、medium、low。数字越界得到 NULL,名称精确匹配失败时可返回指定的无名默认值。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

运行所需文件

在可写目录运行 Rscript --vanilla decisions.R,核对输出和生成的流程图。

下载本章实验包 (mbskycom202612a317.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:R

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a317.zip

下载课程关联工程包:R

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a328.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

先满足至少 12 的条件,结果变为 medium。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习