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

dplyr 1.0.2中重命名特定前缀列的推荐方法及vars()使用疑问

关于dplyr中重命名列的疑问与解决方案

你的理解完全正确!

从dplyr 1.0.0版本开始,官方就正式推荐使用across()替代旧的"范围动词"(比如rename_at()、mutate_at()、select_at()等),而vars()确实是仅为这些旧范围动词设计的辅助函数。在现代dplyr工作流中,vars()已经不再需要使用,甚至在新版本中使用它还可能触发弃用警告。

dplyr 1.0.2中重命名列的推荐方法

针对你的需求——移除所有以Abundance.开头的列名前缀,我们可以用rename()配合across()来实现,这是官方推荐的现代语法:

首先,先确认你的数据结构(方便复现):

xx <- structure(
  list(
    Abundance.126 = c(22.3, 24.5), 
    Abundance.127N = c(23.4, 22.7), 
    Abundance.127C = c(16.6, 21.2), 
    Abundance.128N = c(19.6, 22.8), 
    Abundance.128C = c(23.2, 25.9), 
    Abundance.129N = c(22.7, 25.6), 
    Abundance.129C = c(20.7, 35.2), 
    Abundance.130N = c(17, 33.9), 
    Abundance.130C = c(18.1, 25.8), 
    Abundance.131N = c(20.3, 28.9), 
    Abundance.131C = c(18.8, 31.2), 
    Abundance.132N = c(17.1, 36.8), 
    Abundance.132C = c(19, 41.5), 
    Abundance.133N = c(19.2, 35.3), 
    Abundance.133C = c(21.7, 43.9), 
    Abundance.134N = c(19.6, 53.2)
  ), 
  row.names = 1:2, 
  class = "data.frame"
)

方案1:精准匹配前缀(推荐)

用starts_with()精准定位所有以Abundance.开头的列,比contains()更严谨:

library(dplyr)

xx_renamed <- xx %>%
  rename(across(starts_with("Abundance."), ~sub("Abundance\\.", "", .)))

方案2:匹配包含指定字符串的列(和你原逻辑一致)

如果你需要保留原有的contains()匹配逻辑,也可以这样写:

xx_renamed <- xx %>%
  rename(across(contains("Abundance."), ~sub("Abundance\\.", "", .)))

关键说明:

  • across()是dplyr 1.0.0+的核心多列操作函数,负责指定要操作的列范围和对应的处理函数
  • 注意sub()中的点号要转义为\\.,因为点在正则表达式中是匹配任意字符的通配符,转义后才会匹配实际的点号
  • 这个方法完全替代了旧的rename_at()语法,在dplyr 1.0.2中完全支持,不会触发任何弃用警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:17:32