首页 > 解决方案 > 如何在 R 中运行 SQL 左连接?

问题描述

R 相对较新,我无法在网上找到相当于 SQL 的东西left join。假设我有如下数据:

School| Year| Grade              | #students | math_approached| math_metorexceeded
610534| 2016| Mathematics Grade 3| 57        | 5.3%           | 94.7%
610534| 2016| Mathematics Grade 4| 60        | 8.3%           | 91.7%
610534| 2016| Mathematics Grade 5| 59        | 6.8%           | 93.2%
610534| 2015| Mathematics Grade 3| 57        | 5.3%           | 94.7%
610534| 2015| Mathematics Grade 4| 60        | 8.3%           | 91.7%
610534| 2015| Mathematics Grade 5| 59        | 6.8%           | 93.2%
699999| 2015| Mathematics Grade 3| 51        | 5.3%           | 94.7%
699999| 2015| Mathematics Grade 4| 61        | 8.3%           | 91.7%
699999| 2015| Mathematics Grade 5| 53        | 6.8%           | 93.2%

我正在尝试找到学校年级前一年的数学百分比接近值。在 SQL 中,这看起来像

select a.*, b.math_approached, b.math_metorexceeded
from mydata as a
left join mydata as b
  on a.school = b.school
  and a.grade = b.grade
  and b.year = '2015'
  and a.year = '2016'

回到 R 中,我有一个df保存所有数据的数据框。它有

df$school
df$year
df$grade
df$students
df$math..approached
df$math..met.or.exceeded

作为它的列

标签: r

解决方案


您可以使用的一个选项(需要最少的额外工作)是使用该sqldf包,它允许您在 R 中对您的数据帧运行实际的 SQL 查询。代码很简单:

library(sqldf)

query <- "select a.*, b.math_approached, b.math_metorexceeded
    from df as a
    left join df as b
        on a.school = b.school
        and a.grade = b.grade
        and b.year = '2015'
        and a.year = '2016'"

result <- sqldf(query)

我必须对原始 SQL 查询进行的唯一更改是将 SQL 表名替换为mydataR 中包含相同信息的数据框的名称,df.


推荐阅读