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。

switch 的数字与名称规则
数字形式先把选择值转成整数,再从 1 起数备选项。2.9 转成 2。越界时返回不可见的 NULL。选择表达式可以在运行时计算。
字符形式按名称精确匹配。没有完全匹配且没有未命名备选项时返回 NULL。一个未命名备选项可以处理无匹配的情况,多个未命名项在没有匹配时会报错。
遇到重复名称时使用首个匹配项。字符形式的匹配项若有名称但没有表达式,会继续到后面的非空备选项。普通选择只求值选中的分支,因此未选的 stop() 不会运行。
运行判断链、边界与 switch
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,名称精确匹配失败时可返回指定的无名默认值。
所需环境:基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。
当前源码 SHA256:78a6d339318a0500ff2792fed48135f82109a9cf68a40d500b63196df8d0c8f1
运行所需文件
在可写目录运行 Rscript --vanilla decisions.R,核对输出和生成的流程图。
所需环境:基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。
ZIP SHA256:c543d2d92cca3283321d280e7184e448d3cf2e654dcec4dc379bdf2d227dd27c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
如果交换两个阈值判断的顺序,读数 19 会怎样?
展开参考解答
先满足至少 12 的条件,结果变为 medium。