Case_when 即使不满足条件,似乎也执行代码,见下文:
df <- tibble(
group = c('A', 'A', 'B', 'C'),
take_max = c(F, F, T, T),
value = c(NA, NA, 2, 3)
)
df %>%
group_by(group) %>%
mutate(
res = case_when(
take_max ~ max(value, na.rm = T),
TRUE ~ 1
)
)
Run Code Online (Sandbox Code Playgroud)
case_when 正确计算值,但它也会返回此警告:
Warning: Problem with `mutate()` input `res`.
? no non-missing arguments to max; returning -Inf
? Input `res` is `case_when(take_max ~ max(value, na.rm = T), TRUE ~ 1)`.
? The warning occurred in group 1: group = "A".
Run Code Online (Sandbox Code Playgroud)
为什么case_when在“A”组的情况下甚至计算最大值,而它不应该看到等式的右侧?
您基本上无法在分组设置中不评估右侧。这是 R 的一个基本特性——在对表达式求值之前max(df$value, na.rm = TRUE),R 无法知道从表达式中得到什么。
有两种方法可以解决这个问题:
(1) 在单个组上运行表达式,而不是通过group_bywhich 一次运行所有组
(2) 为 制作一个简单的包装函数max:
SafeMax <- function(x) if (all(is.na(x))) NA_real_ else max(x, na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)
并使用它而不是 max(., na.rm=TRUE)