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

R语言如何将一个数据框列值匹配另一数据框表头并更新数据

解决方案

以下提供两种实现方式,均可满足需求:

方法1:基础R实现(无需额外安装包)

实现思路:先筛选出符合更新条件的完成记录,再逐行匹配更新汇总表

# 筛选completion为1、且属于必修课程的更新记录
update_records <- df_courses[df_courses$completion == 1 & df_courses$course %in% colnames(df_summary), ]

# 逐行遍历更新df_summary
for (i in seq(nrow(update_records))) {
  emp <- update_records$employees[i]
  course <- update_records$course[i]
  # 定位汇总表中对应的行、列索引
  row_idx <- which(df_summary$employees == emp)
  col_idx <- which(colnames(df_summary) == course)
  # 原值不是Not Applicable才执行更新
  if (df_summary[row_idx, col_idx] != "Not Applicable") {
    df_summary[row_idx, col_idx] <- "Completed"
  }
}

方法2:tidyverse实现(长表转换逻辑更简洁)

实现思路:将宽格式的汇总表转为长表,和完成记录关联更新后再转回宽表

library(dplyr)
library(tidyr)

df_summary <- df_summary %>%
  # 把课程列转为长表格式
  pivot_longer(cols = -employees, names_to = "course", values_to = "status") %>%
  # 关联已完成的课程记录
  left_join(df_courses %>% filter(completion == 1), by = c("employees", "course")) %>%
  # 按规则更新状态
  mutate(status = case_when(
    status == "Not Applicable" ~ status,
    completion == 1 ~ "Completed",
    TRUE ~ status
  )) %>%
  # 清理字段,转回原始宽表格式
  select(-completion) %>%
  pivot_wider(names_from = course, values_from = status)

最终更新结果

两种方法执行后得到的df_summary一致:

employeesCourse_ACourse_BCourse_CCourse_DCourse_E
AppleCompletedNot CompletedCompletedNot CompletedNot Completed
BettyCompletedCompletedNot CompletedNot CompletedNot Completed
CarolNot ApplicableNot CompletedNot CompletedNot CompletedCompleted

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:39:03