{"id":18612367,"url":"https://github.com/winvector/rquery","last_synced_at":"2026-01-28T04:47:44.164Z","repository":{"id":56934082,"uuid":"113874307","full_name":"WinVector/rquery","owner":"WinVector","description":"Data Wrangling and Query Generating Operators for R. Distributed under choice of GPL-2 or GPL-3 license.","archived":false,"fork":false,"pushed_at":"2023-08-20T00:52:36.000Z","size":28728,"stargazers_count":109,"open_issues_count":1,"forks_count":15,"subscribers_count":17,"default_branch":"main","last_synced_at":"2024-12-27T02:14:02.538Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://winvector.github.io/rquery/","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WinVector.png","metadata":{"files":{"readme":"README.Rmd","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-12-11T15:16:20.000Z","updated_at":"2024-06-04T14:33:27.000Z","dependencies_parsed_at":"2022-08-21T00:40:28.877Z","dependency_job_id":"2da965a3-d532-4ae7-b3ec-14d748a3b720","html_url":"https://github.com/WinVector/rquery","commit_stats":{"total_commits":1223,"total_committers":3,"mean_commits":407.6666666666667,"dds":"0.012264922322158589","last_synced_commit":"5b8298867e355dc8e99bc90deb42151b579ad537"},"previous_names":[],"tags_count":37,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WinVector%2Frquery","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WinVector%2Frquery/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WinVector%2Frquery/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WinVector%2Frquery/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WinVector","download_url":"https://codeload.github.com/WinVector/rquery/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239402841,"owners_count":19632464,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-07T03:16:50.137Z","updated_at":"2025-11-02T23:30:26.563Z","avatar_url":"https://github.com/WinVector.png","language":"HTML","readme":"---\noutput: github_document\n---\n\n\u003c!-- README.md is generated from README.Rmd. Please edit that file --\u003e\n\n[![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/rquery)](https://cran.r-project.org/package=rquery)\n[![status](https://tinyverse.netlify.com/badge/rquery)](https://CRAN.R-project.org/package=rquery)\n\n\n# `rquery`\n\n[`rquery`](https://winvector.github.io/rquery/) is a piped query generator based on [Codd's relational algebra](https://en.wikipedia.org/wiki/Relational_algebra) (updated to reflect lessons learned from working with [`R`](https://www.r-project.org), [`SQL`](https://en.wikipedia.org/wiki/SQL), and [`dplyr`]( https://CRAN.R-project.org/package=dplyr) at big data scale in production).  \n\n\n\n## Introduction\n\n[`rquery`](https://github.com/WinVector/rquery) is a data wrangling system designed to express complex data manipulation as a series of simple data transforms. This is in the spirit of `R`'s `base::transform()`, or `dplyr`'s `dplyr::mutate()` and uses a pipe in the style popularized in `R` with `magrittr`.  The operators themselves follow the selections in Codd's relational algebra, with the addition of the traditional `SQL` \"window functions.\"  More on the background and context of `rquery` can be found [here](https://github.com/WinVector/rquery/blob/master/Examples/old_readme/README.md).\n\nThe `R`/`rquery` version of this introduction is [here](https://github.com/WinVector/rquery/blob/main/Examples/Introduction/rquery_Introduction.md), and the `Python`/`data_algebra` version of this introduction is [here](https://github.com/WinVector/data_algebra/blob/main/Examples/Introduction/data_algebra_Introduction.ipynb).\n\nIn transform formulations data manipulation is written as transformations that produce new `data.frame`s, instead of as alterations of a primary data structure (as is the case with `data.table`).  Transform system *can* use more space and time than in-place methods. However, in our opinion, transform systems have a number of pedagogical advantages.\n\nIn `rquery`'s case the primary set of data operators is as follows:\n\n * `drop_columns` \n * `select_columns`\n * `rename_columns`\n * `select_rows`\n * `order_rows`\n * `extend`\n * `project`\n * `natural_join`\n * `convert_records` (supplied by the [`cdata` package](https://github.com/WinVector/cdata)).\n\nThese operations break into a small number of themes:\n\n * Simple column operations (selecting and re-naming columns).\n * Simple row operations (selecting and re-ordering rows).\n * Creating new columns or replacing columns with new calculated values.\n * Aggregating or summarizing data.\n * Combining results between two `data.frame`s.\n * General conversion of record layouts  (supplied by the [`cdata` package](https://github.com/WinVector/cdata)).\n \nThe point is: Codd worked out that a great number of data transformations can be decomposed into a small number of the above steps.  `rquery` supplies a high performance implementation of these methods that scales from in-memory scale up through big data scale (to just about anything that supplies a sufficiently powerful `SQL` interface, such as PostgreSQL, Apache Spark, or Google BigQuery).\n\nWe will work through simple examples/demonstrations of the `rquery` data manipulation operators.\n\n## `rquery` operators\n\n### Simple column operations (selecting and re-naming columns)\n\nThe simple column operations are as follows.\n\n * `drop_columns` \n * `select_columns`\n * `rename_columns`\n \nThese operations are easy to demonstrate.\n\nWe set up some simple data.\n\n```{r}\nd \u003c- data.frame(\n  x = c(1, 1, 2),\n  y = c(5, 4, 3),\n  z = c(6, 7, 8)\n)\n\nknitr::kable(d)\n```\n\nFor example: `drop_columns` works as follows. `drop_columns` creates a new `data.frame` without certain columns.\n\n```{r}\nlibrary(rquery)\nlibrary(rqdatatable)\n\ndrop_columns(d, c('y', 'z'))\n```\n\nIn all cases the first argument of a `rquery` operator is either the data to be processed, or an earlier `rquery` pipeline to be extended.  We will take about composing `rquery` operations after we work through examples of all of the basic operations.\n\nWe can write the above in piped notation (using the [`wrapr` pipe](https://journal.r-project.org/archive/2018/RJ-2018-042/index.html) in this case):\n\n```{r}\nd %.\u003e%\n  drop_columns(., c('y', 'z')) %.\u003e%\n  knitr::kable(.)\n```\n\nNotice the first argument is an explicit \"dot\" in [`wrapr` pipe notation](https://journal.r-project.org/archive/2018/RJ-2018-042/index.html).\n\n`select_columns`'s action is also obvious from example.\n\n```{r}\nd %.\u003e%\n  select_columns(., c('x', 'y')) %.\u003e%\n  knitr::kable(.)\n```\n\n`rename_columns` is given as name-assignments of the form `'new_name' = 'old_name'`:\n\n```{r}\nd %.\u003e%\n  rename_columns(., \n                 c('x_new_name' = 'x', \n                   'y_new_name' = 'y')\n                 ) %.\u003e%\n  knitr::kable(.)\n```\n\n### Simple row operations (selecting and re-ordering rows)\n\nThe simple row operations are:\n\n * `select_rows`\n * `order_rows`\n\n`select_rows` keeps the set of rows that meet a given predicate expression.\n\n```{r}\nd %.\u003e%\n  select_rows(., x == 1) %.\u003e%\n  knitr::kable(.)\n```\n\nNotes on how to use a variable to specify column names in `select_rows` can be found [here](https://github.com/WinVector/rquery/blob/master/Examples/Substitution/Substitution.md).\n\n\n`order_rows` re-orders rows by a selection of column names (and allows reverse ordering by naming which columns to reverse in the optional `reverse` argument).  Multiple columns can be selected in the order, each column breaking ties in the earlier comparisons.\n\n```{r}\nd %.\u003e%\n  order_rows(., \n             c('x', 'y'),\n             reverse = 'x') %.\u003e%\n  knitr::kable(.)\n```\n\nGeneral `rquery` operations do not depend on row-order and are not guaranteed to preserve row-order, so if you do want to order rows you should make it the last step of your pipeline.\n\n### Creating new columns or replacing columns with new calculated values\n\nThe important create or replace column operation is:\n\n * `extend`\n\n`extend` accepts arbitrary expressions to create new columns (or replace existing ones).  For example:\n\n```{r}\nd %.\u003e%\n  extend(., zzz := y / x) %.\u003e%\n  knitr::kable(.)\n```\n\nWe can use `=` or `:=` for column assignment.  In these examples we will use `:=` to keep column assignment clearly distinguishable from argument binding.\n\n`extend` allows for very powerful per-group operations akin to what [`SQL`](https://en.wikipedia.org/wiki/SQL) calls [\"window functions\"](https://en.wikipedia.org/wiki/SQL_window_function).  When the optional `partitionby` argument is set to a vector of column names then aggregate calculations can be performed per-group.  For example.\n\n```{r}\nshift \u003c- data.table::shift\n\nd %.\u003e%\n  extend(.,\n         max_y := max(y),\n         shift_z := shift(z),\n         row_number := row_number(),\n         cumsum_z := cumsum(z),\n         partitionby = 'x',\n         orderby = c('y', 'z')) %.\u003e%\n  knitr::kable(.)\n```\n\nNotice the aggregates were performed per-partition (a set of rows with matching partition key values, specified by `partitionby`) and in the order determined by the `orderby` argument (without the `orderby` argument order is not guaranteed, so always set `orderby` for windowed operations that depend on row order!).\n\nMore on the window functions can be found [here](https://github.com/WinVector/rquery/blob/master/Examples/WindowFunctions/WindowFunctions.md). Notes on how to use a variable to specify column names in `extend` can be found [here](https://github.com/WinVector/rquery/blob/master/Examples/Substitution/Substitution.md).\n\n\n\n### Aggregating or summarizing data\n\nThe main aggregation method for `rquery` is:\n\n * `project`\n \n`project` performs per-group calculations, and returns only the grouping columns (specified by `groupby`) and derived aggregates.  For example:\n\n```{r}\nd %.\u003e%\n  project(.,\n         max_y := max(y),\n         count := n(),\n         groupby = 'x') %.\u003e%\n  knitr::kable(.)\n```\n\nNotice we only get one row for each unique combination of the grouping variables.  We can also aggregate into a single row by not specifying any `groupby` columns.\n\n```{r}\nd %.\u003e%\n  project(.,\n         max_y := max(y),\n         count := n()) %.\u003e%\n  knitr::kable(.)\n```\n\nNotes on how to use a variable to specify column names in `project` can be found [here](https://github.com/WinVector/rquery/blob/master/Examples/Substitution/Substitution.md).\n\n### Combining results between two `data.frame`s\n\nTo combine multiple tables in `rquery` one uses what we call the `natural_join` operator.  In the `rquery` `natural_join`, rows are matched by column keys and any two columns with the same name are *coalesced* (meaning the first table with a non-missing values supplies the answer).  This is easiest to demonstrate with an example.\n\nLet's set up new example tables.\n\n```{r}\nd_left \u003c- data.frame(\n  k = c('a', 'a', 'b'),\n  x = c(1, NA, 3),\n  y = c(1, NA, NA),\n  stringsAsFactors = FALSE\n)\n\nknitr::kable(d_left)\n```\n\n```{r}\nd_right \u003c- data.frame(\n  k = c('a', 'b', 'q'),\n  y = c(10, 20, 30),\n  stringsAsFactors = FALSE\n)\n\nknitr::kable(d_right)\n```\n\nTo perform a join we specify which set of columns our our row-matching conditions (using the `by` argument) and what type of join we want (using the `jointype` argument).  For example we can use `jointype = 'LEFT'` to augment our `d_left` table with additional values from `d_right`.\n\n```{r}\nnatural_join(d_left, d_right,\n             by = 'k',\n             jointype = 'LEFT') %.\u003e%\n  knitr::kable(.)\n```\n\nIn a left-join (as above) if the right-table has unique keys then we get a table with the same structure as the left-table- but with more information per row.  This is a very useful type of join in data science projects.  Notice columns with matching names are coalesced into each other, which we interpret as \"take the value from the left table, unless it is missing.\"\n\n\n### General conversion of record layouts\n\nRecord transformation is \"simple once you get it\".  However, we suggest reading up on that as a separate topic [here](https://github.com/WinVector/cdata).\n\n## Composing operations\n\nWe could, of course, perform complicated data manipulation by sequencing `rquery` operations.  For example to select one row with minimal `y` per-`x` group we could work in steps as follows.\n\n```{r}\n. \u003c- d\n. \u003c- extend(.,\n            row_number := row_number(),\n            partitionby = 'x',\n            orderby = c('y', 'z'))\n. \u003c- select_rows(.,\n                 row_number == 1)\n. \u003c- drop_columns(.,\n                  \"row_number\")\nknitr::kable(.)\n```\n\nThe above discipline has the advantage that it is easy to debug, as we can run line by line and inspect intermediate values.  We can even use the [Bizarro pipe](https://win-vector.com/2017/01/29/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/) to make this look like a pipeline of operations.\n\n```{r}\nd -\u003e.;\n  extend(.,\n         row_number := row_number(),\n         partitionby = 'x',\n         orderby = c('y', 'z')) -\u003e.;\n  select_rows(.,\n              row_number == 1)  -\u003e.;\n  drop_columns(.,\n               \"row_number\")    -\u003e.;\n  knitr::kable(.)\n```\n\nOr we can use the [`wrapr` pipe](https://journal.r-project.org/archive/2018/RJ-2018-042/index.html) on the data, which we call \"immediate mode\" (for more on modes please see [here](https://github.com/WinVector/rquery/blob/master/Examples/Modes/Modes.md)).\n\n```{r}\nd %.\u003e%\n  extend(.,\n         row_number := row_number(),\n         partitionby = 'x',\n         orderby = c('y', 'z')) %.\u003e%\n  select_rows(.,\n              row_number == 1)  %.\u003e%\n  drop_columns(.,\n               \"row_number\")    %.\u003e%\n  knitr::kable(.)\n```\n\n`rquery` operators can also act on `rquery` pipelines instead of acting on data. We can write our operations as follows:\n\n```{r}\nops \u003c- local_td(d) %.\u003e%\n  extend(.,\n         row_number := row_number(),\n         partitionby = 'x',\n         orderby = c('y', 'z')) %.\u003e%\n  select_rows(.,\n              row_number == 1)  %.\u003e%\n  drop_columns(.,\n               \"row_number\")\n\ncat(format(ops))\n```\n\nAnd we can re-use this pipeline, both on local data and to generate `SQL` to be run in remote databases. Applying this operator pipeline to our `data.frame` `d` is performed as follows.\n\n```{r}\nd %.\u003e% \n  ops %.\u003e%\n  knitr::kable(.)\n```\n\nAnd for `SQL` we have the following.\n\n```{r}\nraw_connection \u003c- DBI::dbConnect(RSQLite::SQLite(), \":memory:\")\nRSQLite::initExtension(raw_connection)\ndb \u003c- rquery_db_info(\n  connection = raw_connection,\n  is_dbi = TRUE,\n  connection_options = rq_connection_tests(raw_connection))\n\ncat(to_sql(ops, db))\n\n# clean up\nDBI::dbDisconnect(raw_connection)\n```\n\nFor more `SQL` examples, please see [here](https://github.com/WinVector/rquery/tree/master/db_examples).\n\n## Pipeline principles\n\nWhat we are trying to illustrate above: there is a continuum of notations possible between:\n\n * Working over values with explicit intermediate variables.\n * Working over values with a pipeline.\n * Working over operators with a pipeline.\n\nBeing able to see these as all related gives some flexibility in decomposing problems into solutions.  We have some more advanced notes on the differences in working modalities [here](https://github.com/WinVector/rquery/blob/master/Examples/Modes/Modes.md) and [here](https://github.com/WinVector/rquery/blob/master/Examples/Arrow/Arrow.md).\n\n\n## Conclusion\n\n`rquery` supplies a very teachable grammar of data manipulation based on Codd's relational algebra and experience with pipelined data transforms (such as `base::transform()`, `dplyr`, and `data.table`).  \n\nFor in-memory situations `rquery` uses `data.table` as the implementation provider (through the small adapter package `rqdatatable`) and is routinely faster than any other `R` data manipulation system *except* `data.table` itself.\n\nFor bigger than memory situations `rquery` can translate to any sufficiently powerful `SQL` dialect, allowing `rquery` pipelines to be executed on PostgreSQL, Apache Spark, or Google BigQuery.\n\nIn addition the [`data_algebra`](https://github.com/WinVector/data_algebra) Python package supplies a nearly identical system for working with data in Python. \n# Background\n\nThere are many prior relational algebra inspired specialized query languages.  Just a few include:\n\n  * [`Alpha`](https://en.wikipedia.org/wiki/Alpha_(programming_language)) ~1971.\n  * `ISBL` / Information system based language ~1973\n  * [`QUEL`](https://en.wikipedia.org/wiki/QUEL_query_languages) ~1974.\n  * [`IBM System R`](https://en.wikipedia.org/wiki/IBM_System_R) ~1974.\n  * [`SQL`](https://en.wikipedia.org/wiki/SQL) ~1974.\n  * `Tutorial D` ~1994.\n  * [`data.table`](https://rdatatable.gitlab.io/data.table/) ~2006.\n  * [`LINQ`](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) ~2007.\n  * [`pandas`](https://pandas.pydata.org) ~2008.\n  * [`dplyr`](https://dplyr.tidyverse.org) ~2014.\n  * [`Apache Calcite`](https://calcite.apache.org) ~2014.\n \n`rquery` is realized as a thin translation to an underlying `SQL` provider.  We are trying to put the Codd relational operators front and center (using the original naming, and back-porting `SQL` progress such as window functions to the appropriate relational operator).\n\nSome related work includes:\n\n * [`data.table`](https://rdatatable.gitlab.io/data.table/)\n * [`disk.frame`](https://github.com/DiskFrame/disk.frame)\n * [`dbplyr`](https://dbplyr.tidyverse.org)\n * [`dplyr`](https://dplyr.tidyverse.org)\n * [`dtplyr`](https://github.com/tidyverse/dtplyr)\n * [`maditr`](https://github.com/gdemin/maditr)\n * [`nc`](https://github.com/tdhock/nc)\n * [`poorman`](https://github.com/nathaneastwood/poorman)\n * [`rqdatatable`](https://github.com/WinVector/rqdatatable)\n * [`SparkR`]( https://CRAN.R-project.org/package=SparkR)\n * [`sparklyr`](https://spark.rstudio.com)\n * [`sqldf`](https://github.com/ggrothendieck/sqldf)\n * [`table.express`](https://github.com/asardaes/table.express)\n * [`tidyfast`](https://github.com/TysonStanley/tidyfast)\n * [`tidyfst`](https://github.com/hope-data-science/tidyfst)\n * [`tidyquery`](https://github.com/ianmcook/tidyquery)\n * [`tidyr`](https://tidyr.tidyverse.org)\n * [`tidytable`](https://github.com/markfairbanks/tidytable) (formerly `gdt`/`tidydt`)\n * [`data_algebra`](https://github.com/WinVector/data_algebra)\n\n\n# Installing\n\nTo install `rquery` please try `install.packages(\"rquery\")`.\n\n\n# Note\n\n`rquery` is intended to work with \"tame column names\", that is column names that are legitimate symbols in `R` and `SQL`.\n\nThe previous `rquery` introduction is available [here](https://github.com/WinVector/rquery/blob/master/Examples/old_readme/README.md).\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinvector%2Frquery","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwinvector%2Frquery","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinvector%2Frquery/lists"}