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

如何在多个R数据框中匹配对应列并生成目标列final

问题解决:按需求关联并合并R数据框

原始数据定义

emp <- data.frame(
  hi_ras1_55 = c(1:5), 
  kk.ras2_ml= c(6:10),
  ii_ras4.kj = c(11:15)) 

pp <- data.frame(
  emp_id = c (1:5), 
  emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
  salary = c("ras1","ras2","ras3","ras3","ras4")) 

dat <- data.frame(
  gg = c(21:25), 
  Rick= c(6:10))

需求

  • 提取dat第二列的列名“Rick”
  • 在pp中找到emp_name为“Rick”对应的salary值“ras1”
  • 在emp中找到名称包含“ras1”的列
  • 将该列添加到dat,命名为“final”

解决方案代码

# 提取dat第二列的列名
target_name <- colnames(dat)[2]

# 在pp中找到对应salary值
target_ras <- pp$salary[pp$emp_name == target_name]

# 在emp中找到包含target_ras的列
target_col <- emp[, grepl(target_ras, colnames(emp))]

# 添加到dat并命名为final
dat$final <- target_col

# 查看结果
dat

代码解释

  1. colnames(dat)[2]直接取dat的第二列列名,得到“Rick”;
  2. 通过pp$emp_name == target_name筛选出pp中emp_name等于“Rick”的行,再提取对应的salary值,得到“ras1”;
  3. grepl(target_ras, colnames(emp))匹配emp中列名包含“ras1”的列,提取该列数据;
  4. 将提取的列赋值给dat$final,完成添加;
  5. 运行dat即可得到期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:27:13