合并R中的数据帧而不重复

Kat*_*ina 0 merge join r dataframe

我在 R 中遇到一个与此类似的问题:

将 pandas 数据框与关键重复项合并

在 R 中做到这一点应该不难,但我只是找不到解决方案。

非常感谢您的帮助!

akr*_*run 5

通过“key”在每个数据中创建一个序列列,然后执行full_join

library(dplyr)
library(data.table)
df1 %>%
    mutate(rn = rowid(key)) %>% 
   full_join(df2 %>% 
              mutate(rn = rowid(key))) %>%
   select(-rn)
Run Code Online (Sandbox Code Playgroud)

-输出

 key    A    B
1  K0   A0   B0
2  K1   A1   B1
3  K2   A2   B2
4  K2   A3   B3
5  K2   A4 <NA>
6  K3   A5   B4
7  K3 <NA>   B5
8  K4 <NA>   B6
Run Code Online (Sandbox Code Playgroud)

数据

df1 <- structure(list(key = c("K0", "K1", "K2", "K2", "K2", "K3"), A = c("A0", 
"A1", "A2", "A3", "A4", "A5")), class = "data.frame", 
row.names = c("0", 
"1", "2", "3", "4", "5"))

df2 <- structure(list(key = c("K0", "K1", "K2", "K2", "K3", "K3", "K4"
), B = c("B0", "B1", "B2", "B3", "B4", "B5", "B6")), 
class = "data.frame", row.names = c("0", 
"1", "2", "3", "4", "5", "6"))
Run Code Online (Sandbox Code Playgroud)