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

如何基于列索引批量重命名除ID外的数据框列

动态重命名除指定列外的所有列并追加列索引

示例数据框

df <- tibble(
    ID = 1:3,
    col_x = LETTERS[1:3],
    col_q = letters[1:3],
    col_w = 3:1
)

输出结果:

> df
# A tibble: 3 × 4
     ID col_x col_q col_w
  <int> <chr> <chr> <int>
1     1 A     a         3
2     2 B     b         2
3     3 C     c         1

需求

重命名除ID列外的所有列,为列名追加排除ID列后的列索引,期望输出如下:

ID col_x1 col_q2 col_w3
  <int> <chr>  <chr>   <int>
1     1 A      a           3
2     2 B      b           2
3     3 C      c           1

(后续会移除列名中原有的x、q、w)

已尝试的代码

df %>% rename_with(~paste0(.x, 1), .cols = -ID)               # 可行,但所有列都追加1,不符合需求
df %>% rename_with(~paste0(.x, col_number()), .cols = -ID)    # 无效果
df %>% rename_with(~paste0(.x, col_number()-1), .cols = -ID)  # 报错:non-numeric argument to binary operator

注意:col_number()来自readr包,和dplyr的row_number()行为不同,无法直接用来获取列的索引。

动态解决方案

因为列数不固定,需要自动生成对应索引,以下两种方法都可以实现:

方法1:利用cur_column()和match匹配索引

library(dplyr)

df %>% 
  rename_with(
    ~paste0(.x, match(cur_column(), setdiff(names(.), "ID"))),
    .cols = -ID
  )

方法2:直接生成对应长度的序列(更简洁)

df %>% 
  rename_with(
    ~paste0(.x, seq_along(.)),
    .cols = -ID
  )

解释:seq_along(.)会根据-ID筛选后的列数量,生成从1开始的连续整数,正好对应排除ID后的列索引,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:18