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

如何在R语言中实现匹配最高codetype值的左连接?

解决方案

要实现仅保留indcodelist匹配且codetype值最高的左连接结果,可先对secondtable预处理,筛选出每个indcodelist2分组下codetype最大的记录,再与firsttable执行左连接。

完整代码

library(dplyr)

# 预处理第二个表:每个编码仅保留codetype最高的条目
filtered_second <- secondtable %>%
  group_by(indcodelist2) %>%
  filter(codetype == max(codetype)) %>%
  ungroup()

# 执行左连接
result <- left_join(firsttable, filtered_second, by = c("indcodelist" = "indcodelist2"))

# 查看结果
print(result)

代码说明

  1. 预处理表:通过group_by(indcodelist2)按编码分组,filter(codetype == max(codetype))筛选出每组中codetype最大的记录,确保每个编码仅保留最高类型的条目,避免连接后出现重复行。
  2. 左连接:用预处理后的表与firsttable连接,最终结果中每个indcodelist只会对应一条codetype最高的匹配记录,符合需求。

运行结果

indcodelist estemp projemp nchg          codetitle codetype
1      110000     11      15    4        Accountant       18
2      111000     21      25    4          Doctor       18
3      112000     31      36    5         Lawyer       18
4      113000     41      45    4        Teacher       18
5      114000     51      52    1      Economist       18
6      115000     61      61    0 Financial Analyst       18
7      121000     55      31  -24    Meteorologist       18
8      210000     21      29    8         Dentist       18
9      211000     22      31    9          Editor       18
10     315000    874     899   25     Veterinarian       18

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:35:36