This fails:
library(tidyverse)
myFn <- function(nmbr){
case_when(
nmbr > 3 ~ letters[1:3],
TRUE ~ letters[1:2]
)
}
myFn(4)
# Error: `TRUE ~ letters[1:2]` must be length 3 or one, not 2
# Run `rlang::last_error()` to see where the error occurred.
Why does it fail? Why is case_when built in such a way that its branches can't return different-length vectors? I'd like myFn to work so that I can do things like:
tibble(fruit = c("apple", "grape"),
count = 3:4) %>%
mutate(bowl = myFn(count)) %>%
unnest(col = "bowl")
and get
# A tibble: 5 x 3
fruit count bowl
<chr> <int> <int>
1 apple 3 a
2 apple 3 b
3 grape 4 a
4 grape 4 b
5 grape 4 c
I can get it to work - by writing a non-vectorized myFn using if/else, then wrapping it in map, but why should I have to?