为何R语言中case_when函数在两种不同写法下输出结果存在差异?
case_when usages produce different outputs? Let's break down exactly what's happening here—it all comes down to how dplyr::case_when evaluates its right-hand side (RHS) expressions.
The Key Rule About case_when
First, a critical detail from the case_when documentation that explains everything: case_when evaluates all RHS expressions first, then picks the result corresponding to the first TRUE left-hand side (LHS) condition. It doesn't stop evaluating expressions once it finds a matching condition—all of them run upfront.
Analysis of Option 1
Let's walk through your first code snippet step by step:
x = 5 y = print("goodmorning") z = print("goodafternoon") q = print("goodevening") case_when(x > 3 ~ y, x < 8 ~ z)
- When you assign
y = print("goodmorning"), theprint()function runs immediately: it outputs"goodmorning"and assigns the string"goodmorning"toy. Same forzandq—theirprint()calls execute right away, producing their respective outputs. - When
case_whenruns, it only needs to reference the already-computed values ofyandz. It checks the first condition (x > 3is TRUE) and returnsy's value ("goodmorning").
The output you listed ([1] "goodmorning") is likely just the final return value of case_when—if you ran this full code, you'd also see the outputs from z and q's print() calls during assignment.
Analysis of Option 2
Now look at the second snippet:
x = 5 case_when(x > 3 ~ print("goodmoring"), x < 8 ~ print("goodafternoon"))
- Here, the
print()calls are directly on the RHS ofcase_when's conditions. Per the function's behavior, bothprint()calls run upfront, regardless of whether their conditions are eventually used. That's why you see both"goodmoring"and"goodafternoon"printed immediately. - After evaluating all RHS expressions,
case_whenchecks the conditions: the first one (x > 3) is TRUE, so it returns the result of the firstprint()call (which is the string"goodmoring"), hence the third output line.
Summary
- In Option 1,
print()runs outsidecase_when, so they execute once during assignment, andcase_whenjust uses the precomputed values. - In Option 2,
print()is part ofcase_when's RHS expressions, so all of them run before any conditions are checked, leading to extra output.
内容的提问来源于stack exchange,提问作者Stan Verweij

