我有两个数据帧,我希望两个合并在一起,但两个都有重复的键。 merge
告诉我它无法做到这一点,我无法找到替代方案。
基本上,我想要数据集中每个名称的所有组合的结果,如下所示。
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'))
答案 0 :(得分:1)
这应该有效:
library(tidyverse)
df_test <- df2 %>%
left_join(df1, by = "name")