antdurrant · GitHub

case_when always returns length-0 option if any option is length-0

I would expect an error as in case_match. This seems to only be an issue if the input to case_when is length 1 - it errors otherwise.

 x <- 5
# silently returns the wrong thing
dplyr::case_when(
    x == 5 ~ "hello",
    x > 10 ~ character(),
    .default = "other"
)
#> character(0)
# errors
dplyr::case_match(
    x,
    5 ~ "hello",
    10 ~ character(),
    .default = "other"
)
#> Error in `dplyr::case_match()`:
#> ! `..2 (right)` must have size 1, not size 0.
packageVersion("dplyr")
#> [1] '1.1.4'
y <- 5:7
# errors out as expected
dplyr::case_when(
    y == 5 ~ "hello",
    y > 10 ~ character(),
    .default = "other"
)
#> Error in `dplyr::case_when()`:
#> ! Can't recycle `..1 (left)` (size 3) to match `..2 (right)` (size 0).
# errors
dplyr::case_match(
    y,
    5 ~ "hello",
    10 ~ character(),
    .default = "other"
)
#> Error in `dplyr::case_match()`:
#> ! `..2 (right)` must have size 3, not size 0.

Created on 2024-09-05 with reprex v2.1.1

Read the original on github.com ↗