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

如何在R语言大型数据框中批量插入指定位置的条件列?

批量生成Confidence列并插入对应Answer列之后(R语言实现)

需求说明

你有一个包含200+参与者、152个Answer列的数据框,需要为每个AnswerX列后生成对应的ConfidenceX列,规则如下:

  • 当AnswerX为1或6时,ConfidenceX = 2
  • 当AnswerX为2或5时,ConfidenceX = 1
  • 其他情况ConfidenceX = 0

方法1:Base R实现(无需额外包)

# 获取所有以Answer开头的列名
answer_cols <- grep("^Answer", names(data), value = TRUE)

# 循环处理每个Answer列
for (col in answer_cols) {
  # 提取列名中的数字后缀
  num_suffix <- sub("Answer", "", col)
  # 生成对应的Confidence列名
  confidence_col <- paste0("Confidence", num_suffix)
  
  # 根据规则计算Confidence值
  data[[confidence_col]] <- ifelse(
    data[[col]] %in% c(1, 6), 2,
    ifelse(data[[col]] %in% c(2, 5), 1, 0)
  )
  
  # 获取当前Answer列的位置,将Confidence列插入到它后面
  col_position <- which(names(data) == col)
  data <- data[, c(1:col_position, ncol(data), (col_position + 1):(ncol(data) - 1))]
}

方法2:dplyr+purrr实现(代码更简洁)

适合熟悉tidyverse工具链的用户,代码可读性更强:

library(dplyr)
library(purrr)

# 获取所有Answer列名
answer_cols <- grep("^Answer", names(data), value = TRUE)

data <- data %>%
  # 批量生成Confidence列
  mutate(
    across(
      all_of(answer_cols),
      ~case_when(
        .x %in% c(1, 6) ~ 2,
        .x %in% c(2, 5) ~ 1,
        TRUE ~ 0
      ),
      .names = "Confidence{gsub('Answer', '', col)}"
    )
  ) %>%
  # 重新排列列,确保每个Answer列后紧跟对应的Confidence列
  select(
    Participants,
    map2(answer_cols, gsub("Answer", "Confidence", answer_cols), ~c(.x, .y)) %>% unlist()
  )

验证结果

运行后你的数据框会自动调整为Participants → Answer1 → Confidence1 → Answer2 → Confidence2 → ...的结构,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:50:26