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

批量重命名DataFrame相似列名:将start_1至start_32改为m1至m32

批量重命名DataFrame列的简洁方法

方法1:使用dplyr的rename_with(推荐,tidyverse风格)

利用正则表达式批量替换列名,一次处理所有目标列:

library(dplyr)
library(stringr)

df <- df %>%
  rename_with(
    ~ str_replace(., "^start_(\\d+)$", "m\\1"),  # 正则替换:将start_后接的数字保留,前缀替换为m
    starts_with("start_")  # 选中所有以start_开头的列
  )

如果需要精确匹配start_1到start_32(避免误改其他类似命名的列),可以把starts_with换成更精准的匹配规则:

df <- df %>%
  rename_with(
    ~ str_replace(., "^start_(\\d+)$", "m\\1"),
    matches("^start_(1[0-9]|2[0-9]|3[012]|[1-9])$")  # 仅匹配1-32范围内的数字后缀
  )

方法2:基础R实现(无需dplyr)

直接修改列名向量,适合轻量场景:

# 批量替换所有匹配的列名
colnames(df) <- gsub("^start_(\\d+)$", "m\\1", colnames(df))

# 若仅修改特定列(避免影响其他无关列)
target_cols <- grep("^start_(\\d+)$", colnames(df), value = TRUE)
colnames(df)[colnames(df) %in% target_cols] <- gsub("^start_", "m", target_cols)

复用方案:封装成通用函数

如果后续需要对其他前缀的列做类似重命名(比如把end_1到end_32改成n1到n32),可以封装成通用函数:

library(dplyr)
library(stringr)

rename_numeric_suffix_cols <- function(df, old_prefix, new_prefix) {
  df %>%
    rename_with(
      ~ str_replace(., paste0("^", old_prefix, "_(\\d+)$"), paste0(new_prefix, "\\1")),
      starts_with(paste0(old_prefix, "_"))
    )
}

# 调用示例:
df <- rename_numeric_suffix_cols(df, "start", "m")  # start_* → m*
df <- rename_numeric_suffix_cols(df, "end", "n")    # end_* → n*

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:45:34