It seems that case_when is evaluating each RHS and using that to determine the length of the result. Is there a way to avoid this? In my actual use case I am always expecting a character(1) so I subscript the result but it feels pretty hacky. It's easy to imagine situations where not every RHS is a valid expression in the current environment.
I expected that the result of the case_when would be the same as the result of evaluating the relevant RHS. In my example, the second LHS is true so I expect the value to be x[2] which is 2. Instead, case_when seems to be evaluating every RHS, deciding that the result should have length 2, and extending the value to c(2, 2).
My actual use case was formatting a result which has varying number of values. Here is an example which is closer to what I was doing:
case when is vectorized. The output of case_when() will always have the same length as x. You are checking for each element of x whether its length equals 1. This is nonsensical.
For your application you likely do not want to use case_when() but a normal if (...) else construct
My real use case is a little more complex. I rewrote it using switch(length(x)+1, ...) and it works as I wanted . (Using length(x)+1 because the length can be 0.)