使用stringr或其他R包实现跨数据集共享ID产品匹配合并的可行性咨询
如何用R的stringr或其他包实现多ID匹配的数据集合并?
原始数据集
数据集A
| ids | name | price |
|---|---|---|
| 1234 | bread | 1.5 |
| 245r7 | butter | 1.2 |
| 123984 | red wine | 5 |
| 43498 | beer | 1 |
| 235897 | cream | 1.8 |
数据集B
| ids | name | price |
|---|---|---|
| 24908 | lait | 1 |
| 1234,089 | pain | 1.7 |
| 77289,43498 | bière | 1.5 |
| 245r7 | beurre | 1.4 |
需求
匹配所有共享至少一个ID的产品,并合并为如下格式的新数据集:
| id | a_name | b_name | a_price | b_price |
|---|---|---|---|---|
| 1234 | bread | pain | 1.5 | 1.7 |
| 245r7 | butter | beurre | 1.2 | 1.4 |
| 43498 | beer | bière | 1 | 1.5 |
解决方案(使用tidyverse工具集)
当然可以搞定!这里我们用R里的tidyverse工具集(包含你提到的stringr)就能轻松实现这个多ID匹配合并的需求,一步步来:
1. 加载所需包
首先确保安装并加载tidyverse(它整合了stringr、dplyr、tidyr等常用数据处理包):
# 如果还没安装,先运行这行 # install.packages("tidyverse") library(tidyverse)
2. 构造原始数据框
先把你提供的数据集转换成R可识别的tibble(数据框的增强版):
# 数据集A df_a <- tibble( ids = c("1234", "245r7", "123984", "43498", "235897"), name = c("bread", "butter", "red wine", "beer", "cream"), price = c(1.5, 1.2, 5, 1, 1.8) ) # 数据集B df_b <- tibble( ids = c("24908", "1234,089", "77289,43498", "245r7"), name = c("lait", "pain", "bière", "beurre"), price = c(1, 1.7, 1.5, 1.4) )
3. 拆分数据集B的多ID列
数据集B里的ids列有多个ID用逗号分隔,我们需要把这些ID拆成单独的行,这样每个ID都能和数据集A匹配:
df_b_clean <- df_b %>% # 用stringr的str_split把逗号分隔的ID拆成列表 mutate(ids = str_split(ids, ",")) %>% # 用tidyr的unnest_longer把列表转成多行,每个ID对应一行数据 unnest_longer(ids)
处理后的df_b_clean会变成这样:
| ids | name | price |
|---|---|---|
| 24908 | lait | 1 |
| 1234 | pain | 1.7 |
| 089 | pain | 1.7 |
| 77289 | bière | 1.5 |
| 43498 | bière | 1.5 |
| 245r7 | beurre | 1.4 |
4. 匹配合并并整理格式
现在用inner_join只保留两个数据集共有的ID,然后重命名列得到你要的格式:
result <- df_a %>% # 按ID匹配两个数据集,只保留双方都有的ID inner_join(df_b_clean, by = c("ids" = "ids")) %>% # 重命名列,区分来自A和B的数据 rename( id = ids, a_name = name.x, b_name = name.y, a_price = price.x, b_price = price.y ) %>% # 按ID排序,让结果更整洁(可选步骤) arrange(id)
运行后打印result,就是你需要的目标数据集:
print(result) #> # A tibble: 3 × 5 #> id a_name b_name a_price b_price #> <chr> <chr> <chr> <dbl> <dbl> #> 1 1234 bread pain 1.5 1.7 #> 2 245r7 butter beurre 1.2 1.4 #> 3 43498 beer bière 1 1.5
关键细节说明
str_split(来自stringr)是处理逗号分隔字符串的核心函数,负责把多ID拆成列表;unnest_longer(来自tidyr)把列表格式的ID展开成多行,这是实现“共享至少一个ID”匹配的关键;inner_join(来自dplyr)只会保留两个数据集中都存在的ID,完美符合你的需求。
内容的提问来源于stack exchange,提问作者teogj
相关产品推荐
相关产品推荐

