You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何R语言中case_when函数在两种不同写法下输出结果存在差异?

Why do these two 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)
  1. When you assign y = print("goodmorning"), the print() function runs immediately: it outputs "goodmorning" and assigns the string "goodmorning" to y. Same for z and q—their print() calls execute right away, producing their respective outputs.
  2. When case_when runs, it only needs to reference the already-computed values of y and z. It checks the first condition (x > 3 is TRUE) and returns y'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"))
  1. Here, the print() calls are directly on the RHS of case_when's conditions. Per the function's behavior, both print() calls run upfront, regardless of whether their conditions are eventually used. That's why you see both "goodmoring" and "goodafternoon" printed immediately.
  2. After evaluating all RHS expressions, case_when checks the conditions: the first one (x > 3) is TRUE, so it returns the result of the first print() call (which is the string "goodmoring"), hence the third output line.

Summary

  • In Option 1, print() runs outside case_when, so they execute once during assignment, and case_when just uses the precomputed values.
  • In Option 2, print() is part of case_when's RHS expressions, so all of them run before any conditions are checked, leading to extra output.

内容的提问来源于stack exchange,提问作者Stan Verweij

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:42:46