R:基于&Quot;OR&Quot;语句的联接 [英] R: Joins based on "OR" Statements

查看:24
本文介绍了R:基于&Quot;OR&Quot;语句的联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R编程语言。假设我有以下两个表:

table_1 = data.frame(id = c("123", "123", "125", "125"), id2 = c("11", "12", "14", "13"),
date_1 = c("2010-01-31","2010-01-31", "2015-01-31", "2018-01-31" ))

table_1$id = as.factor(table_1$id)
table_1$id2 = as.factor(table_1$id2)
table_1$date_1 = as.factor(table_1$date_1)

table_2 = data.frame(id = c("123", "123", "125", "125"), id2 = c("111", "112", "14", "113"),
date_2 = c("2009-01-31","2010-01-31", "2010-01-31", "2010-01-31" ),
date_3 = c("2011-01-31","2010-01-31", "2020-01-31", "2020-01-31" ))


table_2$id = as.factor(table_2$id)
table_2$id2 = as.factor(table_2$id2)
table_2$date_2 = as.factor(table_2$date_2)
table_2$date_3 = as.factor(table_2$date_3)

如果满足以下两个条件之一(即如果Condition_1=True或Condition_2=True,则&Quot;Join&Quot;)

,我想执行";Join";(任何连接都可以,我只是想了解如何执行此操作)

条件_1

  1. 如果TABLE_1$id=TABLE_2$ID

  1. 如果TABLE_1$DATE介于(TABLE_2$DATE_2,TABLE_2$DATE_3)

条件_2

  1. 如果TABLE_1$ID2=TABLE_2$ID2

  1. 如果TABLE_1$DATE介于(TABLE_2$DATE_2,TABLE_2$DATE_3)

我已经尝试了:我知道如何分别执行这两个联接,例如:

library(sqldf)

#Condition_1


final = sqldf("select a.*, b.*
           
       from table_1 a left join table_2 b
       on a.id = b.id and 
          a.date_1 between 
              b.date_2 and
              b.date_3") 


#Condition_2


final_2 = sqldf("select a.*, b.*
           
       from table_1 a left join table_2 b
       on a.id2 = b.id2 and 
          a.date_1 between 
              b.date_2 and
              b.date_3") 

然后我可以将这些文件绑定在一起(并删除完全重复的行):

final_3 = rbind(final, final_2)

final_3 = final_3[!duplicated(final_3[c(1,2,3,4,5,6,7)]),]

我的问题:是否有办法在一个步骤中将这两个表合并在一起,而不是两个单独的步骤?这可以使用Base R或DPLYR来完成吗?

谢谢!

推荐答案

这可以在单个SQL语句中完成,如下所示。

library(sqldf)

sqldf("select distinct * 
  from table_1 a left join table_2 b
  on (a.date_1 between b.date_2 and b.date_3) and 
     (a.id = b.id or a.id2 = b.id2)")

这篇关于R:基于&Quot;OR&Quot;语句的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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