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

使用dplyr实现条件左连接:按Veh和Pert筛选匹配行

数据集与合并需求

数据集1(dat1)

dat1 <- read.table(header=TRUE, text="
ID  Per  Gu  Ta
1123    112301  14  13
1124 112401  14  19
1125 112501 29  25
1126 112601  22  20
")

dat1

运行输出:

ID    Per Gu Ta
1 1123 112301 14 13
2 1124 112401 14 19
3 1125 112501 29 25
4 1126 112601 22 20

数据集2(dat2)

dat2 <- read.table(header=TRUE, text="
ID  Veh  Pert  Ti  ID1
1123    1 1 100 11231
1123 2 1 110 11232
1124 1 1 107 11241
1124 2 1 111 11242
1124 3 2 109 11243
1125 2 2 118 11251
1125 3 3 113 11252
1125 4 1 108 11253
1126 3 4 119 11265
1126 3 1 112 11268
")

dat2

运行输出:

ID Veh Pert  Ti   ID1
1  1123   1    1 100 11231
2  1123   2    1 110 11232
3  1124   1    1 107 11241
4  1124   2    1 111 11242
5  1124   3    2 109 11243
6  1125   2    2 118 11251
7  1125   3    2 113 11252
8  1125   4    1 108 11253
9  1126   3    4 119 11265
10 1126   3    1 112 11268

合并需求

将dat1与dat2按ID进行左连接,每个ID仅匹配dat2中满足以下条件的行:

  • 优先选取Veh值最小的行;
  • 若同一ID下存在多个Veh最小值的行,则进一步选取其中Pert值最小的行。

预期结果

ID   Per    Gu Ta Veh  Pert  Ti  ID1
1123 112301 14 13 1     1    100 11231
1124 112401 14 19 1     1    107 11241
1125 112501 29 25 2     2    118 11251   ### 在dat2的第8行中,Pert的最小值为1,但Veh的值为4;
1126 112601 22 20 3     1    112 11268

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:40:41