我正在使用dplyr::case_when()基于数据框中的几个变量来匹配一系列复杂的条件。作为一名防御性程序员,我想检查我是否已经考虑了所有可能的条件,但我找不到一种优雅的方法来做到这一点。
这是一个励志的例子:
library("tidyverse")
df <- expand_grid(x=c(NA_integer_, 1L, 2L), y=1L:2L)
df %>%
mutate(Case = case_when(
is.na(x) | is.na(y) ~ NA_character_,
x > y ~ "x>y",
x < y ~ "x<y"
))
Run Code Online (Sandbox Code Playgroud)
返回值混合了 NA:我只是传播输入 NA 的“好”和我忘记了可能条件 x==y 的“坏”。
从概念上讲,我想要的是:
df %>%
mutate(Case = case_when(
is.na(x) | is.na(y) ~ NA_character_,
x > y ~ "x>y",
x < y ~ "x<y",
TRUE ~ stop("Unmatched condition")
))
Run Code Online (Sandbox Code Playgroud)
但是(如 dplyr 中明确记录的那样)这将不起作用,因为每个 RHS 表达式总是被评估。以下确实有效:
library("magrittr")
df %>%
mutate(Case = case_when(
is.na(x) | is.na(y) ~ NA_character_, …Run Code Online (Sandbox Code Playgroud)