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

如何在dplyr的mutate中拼接case_when的参数?

解决dplyr::case_when动态公式列表的作用域报错问题

报错根源是提前定义的公式列表绑定了全局环境,而mutate的求值上下文是数据框内部环境,导致公式左侧的变量(如disp)无法被正确解析。以下是几种无需使用attach的解决方法:

  • 方法一:用rlang::inject确保公式在mutate上下文求值
library(dplyr)
library(rlang)

cwl <- list(disp < 100 ~ "<100", disp < 200 ~ "<200", TRUE ~ "high")

datasets::mtcars |> 
  mutate(disp2 = inject(case_when(!!!cwl)))
  • 方法二:修改公式的绑定环境
    通过rlang::set_env将每个公式的环境切换为mutate的当前求值环境:
library(dplyr)
library(rlang)
library(purrr)

cwl <- list(disp < 100 ~ "<100", disp < 200 ~ "<200", TRUE ~ "high")

datasets::mtcars |> 
  mutate(disp2 = case_when(!!!map(cwl, ~ set_env(.x, current_env()))))
  • 方法三:拆分条件与结果动态生成公式
    无需依赖环境处理函数,拆分条件表达式和结果值后动态拼接公式:
library(dplyr)
library(purrr)

conditions <- list(quote(disp < 100), quote(disp < 200), quote(TRUE))
results <- list("<100", "<200", "high")

datasets::mtcars |> 
  mutate(disp2 = case_when(!!!map2(conditions, results, ~ .x ~ .y)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:40:17