简体   繁体   English

多对多合并

[英]Many to Many Merge

I have two dataframes that I wish two merge together, but both have duplicate keys. 我有两个数据框,希望两个可以合并在一起,但是两个键都有重复的键。 merge is telling me it cannot do this, and I cannot figure out an alternative. merge告诉我它不能执行此操作,因此我无法找出替代方案。

Basically, I want the result of all combinations of each name in the dataset, like this. 基本上,我想要数据集中每个名称的所有组合的结果,像这样。

name <- c('Jim', 'Jim', 'Kim')
region <- c('East', 'West', 'North')
df1 <- data.frame(name, region)
name <- c('Jim', 'Jim', 'Kim')
type <- c('Urban', 'Rural', 'Urban')
df2 <- data.frame(name, type)

# this doesn't work
df3 <- merge(df1, df2, by = name, all = TRUE)

# this is what i want
want <- data.frame(name = c('Jim', 'Jim', 'Jim', 'Jim', 'Kim'),
                   region = c('East', 'West', 'East', 'West', 'North'),
                   type = c('Urban', 'Urban', 'Rural', 'Rural', 'Urban'))

This should work: 这应该工作:

library(tidyverse)
df_test <- df2 %>% 
  left_join(df1, by = "name")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM