Home > Mobile >  Why does case_when have two different outputs here?
Why does case_when have two different outputs here?

Time:06-30

I am failing to understand why the output is different when I use two different cases of case_when:

Option 1:

x = 5
y = print("goodmorning")
z = print("goodafternoon")
q = print("goodevening")
case_when(x > 3 ~ y, x < 8 ~ z) 

Output 1:

[1] "goodmorning"

Option 2:

x = 5
case_when(x > 3 ~ print("goodmoring"), x < 8 ~ print("goodafternoon"))

Output 2:

[1] "goodmoring"
[1] "goodafternoon"
[1] "goodmoring"

Can someone enlighten me how this results in two completely different outputs. I believed that case_when sequentially and that it jumps out of the case_case when the first time the a condition is met and this seems to hold for the first piece of code, but why does it not hold for the second code?

CodePudding user response:

Citing the help page (emphasis mine),

case_when() evaluates all RHS expressions, and then constructs its result by extracting the selected (via the LHS expressions) parts

  • Related