如何使用left_join合并三个数据集并设置唯一后缀?
如何用left_join合并三个数据集并给每个的重复列加唯一后缀?
你想合并三个共享x列的数据集,让每个原数据集的y列分别带上.first、.second、.third的唯一后缀,但当前代码合并后第三列是y,不是你想要的y.third。
测试数据
library(tibble) library(dplyr) df1 <- tibble(x = 1:5, y = c("names", "matches", "multiple", "rows", "different")) df2 <- tibble(x = 3:5, y = c("first", "second", "third")) df3 <- tibble(x = 2:4, y = 1:3)
现有代码的问题
你现在写的代码:
left_join(df1, df2, by='x', suffix = c(".first", ".second")) %>% left_join(., df3 , by='x', suffix = c("third", "third"))
之所以最后一列是y,是因为第一次合并后,原df1和df2的y已经被重命名为y.first和y.second,左边的数据集里不再有y这个列。第二次left_join时,只有当左右两边存在同名的非连接列时,suffix参数才会生效,所以df3的y列直接保留了原名。
解决办法
这里有两种简单的实现方式:
方式1:合并前先改df3的列名
直接把df3的y列重命名为y.third再合并,一步到位:
left_join(df1, df2, by='x', suffix = c(".first", ".second")) %>% left_join(., df3 %>% rename(y.third = y), by='x')
方式2:合并后重命名列
如果不想提前修改原始数据集,也可以在合并完成后把新增的y列改成y.third:
left_join(df1, df2, by='x', suffix = c(".first", ".second")) %>% left_join(., df3, by='x') %>% rename(y.third = y)
最终结果
两种方法运行后都能得到你期望的输出:
# # A tibble: 5 × 4 # x y.first y.second y.third # <int> <chr> <chr> <int> # 1 1 names <NA> NA # 2 2 matches <NA> 1 # 3 3 multiple first 2 # 4 4 rows second 3 # 5 5 different third NA
内容的提问来源于stack exchange,提问作者Eric Fail
相关产品推荐
相关产品推荐

