r - 在不使用 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
解决方案
Merge
2 个表 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)
推荐阅读
- html - 悬停时的转换延迟关闭
- python - Pygame 只在按键上前进
- php - Doctrine ArrayCollection 大 O
- android - Handler 的 postDelayed 的回调:检查 FragmentActivity 是否不为 null 且未销毁?
- python - 使用 Python mysql.connector 连接到 MariaDB 的问题
- java - 使用 Logstash 索引从 Cassandra 到 Solr 的项目
- php - 为什么邮件程序在 php 中不起作用,我在哪里弄错了?
- javascript - 在确认弹出窗口(Node、Express、Jade)中单击 Ok 时如何发出 POST 请求而不是 GET
- python-3.x - 如何处理 ValueError:Julian Day 必须是正数
- python - Pyramid 覆盖默认请求日志以添加新参数