pyll
pyll

Reputation: 1764

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.

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'))

Upvotes: 2

Views: 6204

Answers (1)

roarkz
roarkz

Reputation: 831

This should work:

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

Upvotes: 2

Related Questions