繁体   English   中英

如何根据条件连接两个没有共同变量的数据框?

[英]How do I join two dataframes, based on conditions, with no common variable?

我正在尝试在R中重新创建以下SAS代码

PROC SQL;
    create table counts_2018 as 
    select a.*, b.cell_no 
    from work.universe201808 a, work.selpar17 b 
    where a.newregionxx = b.lower_region2 
      and a.froempment >= b.lower_size 
      and a.froempment <= b.upper_size 
      and a.frosic07_2 >= b.lower_class2 
      and a.frosic07_2 <= b.upper_class2;
QUIT;

这个做什么,实际上是分配在selpar17发现在universe201808的数据cell_no的基础上,在代码中概述的所有6个条件的实现。 不能满足这些条件的数据因此不会为其分配cell_no ,这些数据不包含在最终表中。

到目前为止,我发现的文档/答案都从一个步骤开始,在该步骤中,两个数据帧由一个公共变量合并,然后执行sqldf select 我没有公共列,因此无法合并数据框。

当前,您正在两个表之间运行隐式联接,SQL不建议这样做。 根据使显式JOIN成为连接关系的标准方式的ANSI-1992(25年规范),请考虑相应地修改SQL查询。

与您的陈述相反,实际上您在表之间确实有一个相等的列,如相等条件所示: a.newregionxx = b.lower_region2可以用作JOIN条件。 甚至可以使用BETWEEN运算符进行简化:

new_df <- sqldf('select u.*, s.cell_no 
                 from universe201808 u
                 inner join selpar17 s 
                         on u.newregionxx = s.lower_region2 
                 where u.froempment between s.lower_size and s.upper_size 
                   and u.frosic07_2 between s.lower_class2 and s.upper_class2')

实际上,您可以完全删除where并将其on子句中:

...
on u.newregionxx = s.lower_region2 
and u.froempment between s.lower_size and s.upper_size 
and u.frosic07_2 between s.lower_class2 and s.upper_class2

暂无
暂无

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

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