首页 > 解决方案 > 在不使用 for 循环的情况下根据多个条件匹配不同数据帧中的行

问题描述

我的数据包含两个不同的数据框:

visits <- data.frame("visit_nr", "label", "degree", "code")
category <- data.frame("label", "degree", "group", "code1", "code2, "code3")

我想根据两个数据帧之间的“标签”、“度数”和“代码”的匹配,为数据帧“访问”中的每次访问分配一个组。但是,如果数据帧“类别”中的“code2”和“code3”也列在数据帧“visits”中,则来自某个“visit_nr”的行只能分配给特定组。这意味着要将一行分配给某个组,需要有三行具有相同的“visit_nr”,其中“label”;"degree" 和 "code" 与以下任一匹配:

- "label", "degree", "code1"
- "label", "degree", "code2"
- "label", "degree", "code3" 

因为这些数据帧都包含超过 50 000 行,所以我想避免使用循环来完成此操作。

访问

visit_nr   | label | degree | code   |  Group
1601704801 |  171  |    1   | 354373 |   0
1601704801 |  171  |    1   | 200200 |   0
1601704801 |  171  |    1   | 973443 |   0
1601704801 |  171  |    1   | 475985 |   0
1601704801 |  171  |    1   | 994320 |   0

类别

label | degree | group | code1 | code2 | code3
 171  |   1    |   2   | 354373| 200200| 475985 
 171  |   1    |   3   | 354373| 200200| 998282
 171  |   1    |   1   | 354373| 200200| 0

预期输出:

visit_nr   | label | degree | code   |  Group 
1601704801 |  171  |    1   | 354373 |   2
1601704801 |  171  |    1   | 200200 |   2
1601704801 |  171  |    1   | 973443 |   2
1601704801 |  171  |    1   | 475985 |   2
1601704801 |  171  |    1   | 994320 |   2

标签: rdataframemergeleft-joinmatching

解决方案


Merge2 个表 3 次,然后像这样 rbind 全部:

df1 <- merge(visits, category, by.x = c("label", "degree", "code"), by.y = c("label", "degree", "code1"), all.x = TRUE)
df2 <- merge(visits, category, by.x = c("label", "degree", "code"), by.y = c("label", "degree", "code2"), all.x = TRUE)
df3 <- merge(visits, category, by.x = c("label", "degree", "code"), by.y = c("label", "degree", "code3"), all.x = TRUE)
#change the column names using names(df) here to maintain consistency
df <- rbind(df1, df2, df3)

推荐阅读