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

如何用recipes::step_rename复现dplyr::rename的存在列重命名功能?

用recipes::step_rename复现dplyr::rename的功能

方案1:筛选有效映射后用!!!展开命名向量

step_rename支持通过!!!(非标准求值)直接传递新列名=旧列名的命名向量,但需要先过滤掉数据中不存在的旧列,避免报错:

library(recipes)
library(dplyr)

df <- data.frame(a_old = 1:3, b_new = 11:13)
lkp <- c(a_new = "a_old", b_new = "b_old")

# 筛选出数据中存在的旧列对应的映射关系
valid_lkp <- lkp[lkp %in% colnames(df)]

recipe(df) %>%
  step_rename(!!!valid_lkp) %>%
  prep() %>%
  bake(new_data = NULL)

输出结果:

# A tibble: 3 x 2
  a_new b_new
  <int> <int>
1     1    11
2     2    12
3     3    13

方案2:用step_rename_at结合any_of

通过step_rename_at指定要重命名的旧列(用any_of筛选存在的列),再映射到对应的新列名:

library(recipes)
library(dplyr)

df <- data.frame(a_old = 1:3, b_new = 11:13)
lkp <- c(a_new = "a_old", b_new = "b_old")

recipe(df) %>%
  step_rename_at(
    vars(any_of(lkp)),  # 选择数据中存在的旧列
    ~ names(lkp)[match(., lkp)]  # 匹配对应的新列名
  ) %>%
  prep() %>%
  bake(new_data = NULL)

输出结果和方案1一致。

原代码生成奇怪列名的原因

dplyr::rename中的any_of(lkp)会直接解析命名向量的逻辑:将存在的旧列重命名为对应的新列名。但step_rename的参数解析逻辑不同,它不会把any_of(lkp)当作列选择器处理,而是将整个表达式作为新列名的一部分,因此生成了any_of(lkp)...a_new这种异常列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 00:33:25