r - 如何在 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
作为它的列
解决方案
您可以使用的一个选项(需要最少的额外工作)是使用该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 表名替换为mydata
R 中包含相同信息的数据框的名称,df
.
推荐阅读
- javascript - 反应原生:模态总是可见的
- c# - C# 将参数附加到字符串
- reactjs - 图片在 React 中显示为“[object HTMLImageElement]”
- python - 如果存在行分隔符,如何使用 numpy 加载txt
- apache-kafka - 哪些 Runners 在 apache Beam 中支持 kafkaIO?
- zfs - Zfs:如何删除卷?
- python-3.x - Psycopg2 在动态生成的 SQL 上引发语法错误
- javascript - 动态 PHP 分页 Mysqli
- unix - 正则表达式过滤事件
- python - 按不同级别的数据汇总分组之间的差异