查找两个数据帧的唯一对之间的匹配并绑定R中的值 [英] Find matches between unique pairs of two dataframes and bind values in R

查看:85
本文介绍了查找两个数据帧的唯一对之间的匹配并绑定R中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据帧dat1和dat2,我想在两个数据帧的前两列之间找到匹配项,并将每个数据帧中包含的值进行唯一配对.

I have two dataframes dat1 and dat2 and I would like to find matches between the first two columns of the two dataframes and join the values contained in each dataframe for unique pairs.

dat1<-data.frame(V1 = c("home","fire","sofa","kitchen"), 
                V2 = c("cat","water","TV","knife"), V3 = c('date1','date2','date3','date4'))

       V1    V2    V3
1    home   cat date1
2    fire water date2
3    sofa    TV date3
4 kitchen knife date4

dat2<-data.frame(V1 = c("home","water","sofa","knife"), 
                 V2 = c("cat","fire","TV","kitchen"), V3 = c('col1','col2','col3','col4'))

 V1      V2   V3
1  home     cat col1
2 water    fire col2
3  sofa      TV col3
4 knife kitchen col4

所需的结果将是:

 V1      V2    V3   V4
1  home     cat date1 col1
2 water    fire date2 col2
3  sofa      TV date3 col3
4 knife kitchen date4 col4

关于如何在R中执行操作的任何想法?

Any idea on how to do it in R?

推荐答案

您可以创建一个包含相同顺序单词的新列,然后根据该列进行连接:

You can create a new column which contains the words in the same order and join based off that column:

library(dplyr)

dat2 %>% 
  mutate_if(is.factor, as.character) %>% 
  mutate(x = ifelse(V1 > V2, paste(V1, V2), paste(V2, V1))) %>% 
  inner_join(
    dat1 %>% 
      mutate_if(is.factor, as.character) %>% 
      mutate(x = ifelse(V1 > V2, paste(V1, V2), paste(V2, V1))) %>% 
      select(-V1, -V2),
    by = "x"
  ) %>% 
  select(V1, V2, V3 = V3.y, V4 = V3.x)
#     V1      V2    V3   V4
#1  home     cat date1 col1
#2 water    fire date2 col2
#3  sofa      TV date3 col3
#4 knife kitchen date4 col4

这篇关于查找两个数据帧的唯一对之间的匹配并绑定R中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆