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

R语言如何按列名模式合并具有相同前缀的多列数据

解法思路

  1. 从现有列名中提取所有唯一前缀(即_A之前的部分)
  2. 对每个前缀,动态匹配三个后缀对应的列,按要求的格式拼接字符串
  3. 最后仅保留合并后的前缀列即可

tidyverse 方案(适配 mutate+across 写法)

library(tidyverse)

# 示例数据
df1 <- data.frame(col1_A1.5 = c(1,2,3,4), 
                  col1_A2.0 = c(2,3,4,5),
                  col1_A2.5 = c(3,4,5,6),
                  col2_A1.5 = c(10,20,30,40), 
                  col2_A2.0 = c(20,30,40,50),
                  col2_A2.5 = c(30,40,50,60))

result <- df1 %>%
  mutate(
    across(all_of(unique(str_remove(names(.), "_A.*$"))),
           .fns = ~ str_c(
             get(str_replace(cur_column(), "$", "_A2.0")),
             " [",
             get(str_replace(cur_column(), "$", "_A1.5")),
             ", ",
             get(str_replace(cur_column(), "$", "_A2.5")),
             "]"
           ),
           .names = "{.col}")
  ) %>%
  select(all_of(unique(str_remove(names(df1), "_A.*$"))))

无依赖的 Base R 方案

# 提取所有唯一前缀
prefixes <- unique(sub("_A.*$", "", names(df1)))
result <- data.frame(row.names = rownames(df1))

# 遍历前缀批量生成合并列
for (p in prefixes) {
  result[[p]] <- paste0(
    df1[[paste0(p, "_A2.0")]],
    " [",
    df1[[paste0(p, "_A1.5")]],
    ", ",
    df1[[paste0(p, "_A2.5")]],
    "]"
  )
}

两种方案都会自动识别所有同前缀列组,无需手动指定列名,可直接适配100+列的使用场景,输出结果和你给出的期望格式完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:54:03