Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

case_when() evaluating all RHS expressions except only the ones matching LHS #5321

Closed
frederikziebell opened this issue Jun 10, 2020 · 1 comment

Comments

@frederikziebell
Copy link

According to one example in the function documentation

# case_when() evaluates all RHS expressions, and then constructs its
# result by extracting the selected (via the LHS expressions) parts.
# In particular NaN are produced in this case:
y <- seq(-2, 2, by = .5)
case_when(
  y >= 0 ~ sqrt(y),
  TRUE   ~ y
)

Wouldn't it be better to only evaluate the RHS for the instances where the LHS is TRUE and then paste these evaluations together?

If there are five cases evenly distributed across the vector, this means five times more computations. Yes, vectorization is fast, but it's faster to not do computations one is not interested in anyway.

@hadley
Copy link
Member

hadley commented Jun 10, 2020

This is currently needed for type stability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants