You need to enable JavaScript to run this app. 如何使用dplyr的case_when选择列修改tidymodels recipe的列角色?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dplyr的case_when选择列修改tidymodels recipe的列角色?

问题原因
  • update_role() 接收的是列选择规则(tidyselect 语法),你直接在参数内写 case_when() 的写法有两个核心问题:
    1. 你在 case_when 中直接返回 b、.$b 这类值,返回的是列的数值向量,不是列的标识,update_role 无法把数值向量识别为要修改的列
    2. case_when 在 update_role 的参数环境中无法直接解析裸列名,也不会把输出转换为 tidyselect 可识别的列选择规则
解决方法

先通过 case_when 得到目标列的字符串名称,再通过 all_of() 包裹传入 update_role 即可,all_of 是 tidyselect 的标准语法,支持传入字符串向量选择对应列。

正确的可运行代码如下:

library(tidyverse)
library(tidymodels)

# 模拟数据
a = seq(1:3)
b = seq(4:6)
c = seq(7:9)
df <- data.frame(a,b,c)

# 判断条件变量
col_name = "foo"

# 先计算目标列名
target_col <- case_when(
  col_name == "foo" ~ "b",
  col_name == "foo2" ~ "c"
)

rec <- recipe(a ~., data = df) %>%
  update_role(all_of(target_col), new_role = "ID")

# 查看结果确认角色修改成功
summary(rec)

运行后查看 summary(rec) 可以看到列 b 的 role 已经被设置为 ID,符合预期。

补充注意事项
  • 如果你存在 col_name 不匹配任何条件的场景,建议给 case_when 加默认返回值,避免 target_col 为 NA 导致报错
  • 如果要同时匹配多个列,case_when 返回多列名字符串向量即可,all_of 支持多值传入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:24:07