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

如何在R语言中按顺序拼接A系列与B系列的列序列?

解决方法

你之前的代码问题在于str_c无法直接识别starts_with这类tidyselect选择器,必须先正确选取对应列再执行拼接操作。以下是两种可行的实现方式:

方法一:使用dplyr + purrr

加载所需包后,通过列名配对完成逐列拼接:

library(dplyr)
library(purrr)
library(stringr)

df <- data.frame(A_1_1 =  'a',
                 A_2_1 =  'b',
                 A_3_1 =  'c',
                 B_0_1 =  'x',
                 B_0_2 =  'y',
                 B_0_3 =  'z'
)

df_combined <- df %>%
  mutate(
    # 获取A、B系列的列名列表
    A_list = select(., starts_with("A_")) %>% names(),
    B_list = select(., starts_with("B_")) %>% names(),
    # 逐对拼接列内容,生成新列
    !!!set_names(
      map2(A_list, B_list, ~ str_c(!!sym(.x), "-", !!sym(.y))),
      paste0("combined_", seq_along(A_list))
    )
  )

# 查看拼接后的结果列
select(df_combined, starts_with("combined_"))

执行后会生成combined_1、combined_2、combined_3三列,对应结果为a-x、b-y、c-z。

方法二:使用Base R

无需额外加载包,直接通过基础语法实现:

df <- data.frame(A_1_1 =  'a',
                 A_2_1 =  'b',
                 A_3_1 =  'c',
                 B_0_1 =  'x',
                 B_0_2 =  'y',
                 B_0_3 =  'z'
)

# 筛选出A、B系列的列
A_cols <- df[, startsWith(names(df), "A_")]
B_cols <- df[, startsWith(names(df), "B_")]

# 逐列拼接生成新数据框
combined_df <- data.frame(mapply(function(a_col, b_col) paste(a_col, b_col, sep = "-"), A_cols, B_cols))
names(combined_df) <- paste0("combined_", 1:ncol(combined_df))

# 合并到原数据框(可选操作)
df_combined <- cbind(df, combined_df)

关键注意点

  • 必须保证A、B系列的列数一致且顺序对应,否则拼接会出现不匹配的问题;
  • starts_with是tidyselect语法,仅能在select等支持该语法的函数中使用,不能直接传递给str_c。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:35:35