Free Access Week - Data Engineering + BI
Data Engineering and BI courses are free this week!
Free Access Week - Jun 2-8

⚠️There's a newer version (1.4.99) of this package.Take me there.

rquery

rquery is a piped query generator based on Codd’s relational algebra (updated to reflect lessons learned from working with R, SQL, and dplyr at big data scale in production).

Introduction

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.

The R/rquery version of this introduction is here, and the Python/data_algebra version of this introduction is here.

In transform formulations data manipulation is written as transformations that produce new data.frames, 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.

In rquery’s case the primary set of data operators is as follows:

  • drop_columns
  • select_columns
  • rename_columns
  • select_rows
  • order_rows
  • extend
  • project
  • natural_join
  • convert_records (supplied by the cdata package).

These operations break into a small number of themes:

  • Simple column operations (selecting and re-naming columns).
  • Simple row operations (selecting and re-ordering rows).
  • Creating new columns or replacing columns with new calculated values.
  • Aggregating or summarizing data.
  • Combining results between two data.frames.
  • General conversion of record layouts (supplied by the cdata package).

The 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).

We will work through simple examples/demonstrations of the rquery data manipulation operators.

rquery operators

Simple column operations (selecting and re-naming columns)

The simple column operations are as follows.

  • drop_columns
  • select_columns
  • rename_columns

These operations are easy to demonstrate.

We set up some simple data.

d <- data.frame(
  x = c(1, 1, 2),
  y = c(5, 4, 3),
  z = c(6, 7, 8)
)

knitr::kable(d)
xyz
156
147
238

For example: drop_columns works as follows. drop_columns creates a new data.frame without certain columns.

library(rquery)
library(rqdatatable)

drop_columns(d, c('y', 'z'))
##    x
## 1: 1
## 2: 1
## 3: 2

In 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.

We can write the above in piped notation (using the wrapr pipe in this case):

d %.>%
  drop_columns(., c('y', 'z')) %.>%
  knitr::kable(.)
x
1
1
2

Notice the first argument is an explicit “dot” in wrapr pipe notation.

select_columns’s action is also obvious from example.

d %.>%
  select_columns(., c('x', 'y')) %.>%
  knitr::kable(.)
xy
15
14
23

rename_columns is given as name-assignments of the form 'new_name' = 'old_name':

d %.>%
  rename_columns(., 
                 c('x_new_name' = 'x', 
                   'y_new_name' = 'y')
                 ) %.>%
  knitr::kable(.)
x_new_namey_new_namez
156
147
238

Simple row operations (selecting and re-ordering rows)

The simple row operations are:

  • select_rows
  • order_rows

select_rows keeps the set of rows that meet a given predicate expression.

d %.>%
  select_rows(., x == 1) %.>%
  knitr::kable(.)
xyz
156
147

Notes on how to use a variable to specify column names in select_rows can be found here.

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.

d %.>%
  order_rows(., 
             c('x', 'y'),
             reverse = 'x') %.>%
  knitr::kable(.)
xyz
238
147
156

General 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.

Creating new columns or replacing columns with new calculated values

The important create or replace column operation is:

  • extend

extend accepts arbitrary expressions to create new columns (or replace existing ones). For example:

d %.>%
  extend(., zzz := y / x) %.>%
  knitr::kable(.)
xyzzzz
1565.0
1474.0
2381.5

We can use = or := for column assignment. In these examples we will use := to keep column assignment clearly distinguishable from argument binding.

extend allows for very powerful per-group operations akin to what SQL calls “window functions”. When the optional partitionby argument is set to a vector of column names then aggregate calculations can be performed per-group. For example.

shift <- data.table::shift

d %.>%
  extend(.,
         max_y := max(y),
         shift_z := shift(z),
         row_number := row_number(),
         cumsum_z := cumsum(z),
         partitionby = 'x',
         orderby = c('y', 'z')) %.>%
  knitr::kable(.)
xyzmax_yshift_zrow_numbercumsum_z
1475NA17
15657213
2383NA18

Notice 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!).

More on the window functions can be found here. Notes on how to use a variable to specify column names in extend can be found here.

Aggregating or summarizing data

The main aggregation method for rquery is:

  • project

project performs per-group calculations, and returns only the grouping columns (specified by groupby) and derived aggregates. For example:

d %.>%
  project(.,
         max_y := max(y),
         count := n(),
         groupby = 'x') %.>%
  knitr::kable(.)
xmax_ycount
152
231

Notice 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.

d %.>%
  project(.,
         max_y := max(y),
         count := n()) %.>%
  knitr::kable(.)
max_ycount
53

Notes on how to use a variable to specify column names in project can be found here.

Combining results between two data.frames

To 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.

Let’s set up new example tables.

d_left <- data.frame(
  k = c('a', 'a', 'b'),
  x = c(1, NA, 3),
  y = c(1, NA, NA),
  stringsAsFactors = FALSE
)

knitr::kable(d_left)
kxy
a11
aNANA
b3NA
d_right <- data.frame(
  k = c('a', 'b', 'q'),
  y = c(10, 20, 30),
  stringsAsFactors = FALSE
)

knitr::kable(d_right)
ky
a10
b20
q30

To 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.

natural_join(d_left, d_right,
             by = 'k',
             jointype = 'LEFT') %.>%
  knitr::kable(.)
kxy
a11
aNA10
b320

In 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.”

General conversion of record layouts

Record transformation is “simple once you get it”. However, we suggest reading up on that as a separate topic here.

Composing operations

We 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.

. <- d
. <- extend(.,
            row_number := row_number(),
            partitionby = 'x',
            orderby = c('y', 'z'))
. <- select_rows(.,
                 row_number == 1)
. <- drop_columns(.,
                  "row_number")
knitr::kable(.)
xyz
147
238

The 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 to make this look like a pipeline of operations.

d ->.;
  extend(.,
         row_number := row_number(),
         partitionby = 'x',
         orderby = c('y', 'z')) ->.;
  select_rows(.,
              row_number == 1)  ->.;
  drop_columns(.,
               "row_number")    ->.;
  knitr::kable(.)
xyz
147
238

Or we can use the wrapr pipe on the data, which we call “immediate mode” (for more on modes please see here).

d %.>%
  extend(.,
         row_number := row_number(),
         partitionby = 'x',
         orderby = c('y', 'z')) %.>%
  select_rows(.,
              row_number == 1)  %.>%
  drop_columns(.,
               "row_number")    %.>%
  knitr::kable(.)
xyz
147
238

rquery operators can also act on rquery pipelines instead of acting on data. We can write our operations as follows:

ops <- local_td(d) %.>%
  extend(.,
         row_number := row_number(),
         partitionby = 'x',
         orderby = c('y', 'z')) %.>%
  select_rows(.,
              row_number == 1)  %.>%
  drop_columns(.,
               "row_number")

cat(format(ops))
## mk_td("d", c(
##   "x",
##   "y",
##   "z")) %.>%
##  extend(.,
##   row_number := row_number(),
##   partitionby = c('x'),
##   orderby = c('y', 'z'),
##   reverse = c()) %.>%
##  select_rows(.,
##    row_number == 1) %.>%
##  drop_columns(.,
##    c('row_number'))

And 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.

d %.>% 
  ops %.>%
  knitr::kable(.)
xyz
147
238

And for SQL we have the following.

raw_connection <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
RSQLite::initExtension(raw_connection)
db <- rquery_db_info(
  connection = raw_connection,
  is_dbi = TRUE,
  connection_options = rq_connection_tests(raw_connection))

cat(to_sql(ops, db))
## SELECT
##  `x`,
##  `y`,
##  `z`
## FROM (
##  SELECT * FROM (
##   SELECT
##    `x`,
##    `y`,
##    `z`,
##    row_number ( ) OVER (  PARTITION BY `x` ORDER BY `y`, `z` ) AS `row_number`
##   FROM (
##    SELECT
##     `x`,
##     `y`,
##     `z`
##    FROM
##     `d`
##    ) tsql_36251475914729678432_0000000000
##  ) tsql_36251475914729678432_0000000001
##  WHERE `row_number` = 1
## ) tsql_36251475914729678432_0000000002
# clean up
DBI::dbDisconnect(raw_connection)

For more SQL examples, please see here.

Pipeline principles

What we are trying to illustrate above: there is a continuum of notations possible between:

  • Working over values with explicit intermediate variables.
  • Working over values with a pipeline.
  • Working over operators with a pipeline.

Being 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 and here.

Conclusion

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).

For 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.

For 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.

In addition the data_algebra Python package supplies a nearly identical system for working with data in Python. The two systems can even share data manipulation code between each other (allowing very powerful R/Python inter-operation or helping port projects from one to the other).

Background

There are many prior relational algebra inspired specialized query languages. Just a few include:

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).

Note

rquery is intended to work with “tame column names”, that is column names that are legitimate symbols in R and SQL.

The previous rquery introduction is available here.

Installing

To install rquery please try install.packages("rquery").

Copy Link

Version

Install

install.packages('rquery')

Monthly Downloads

2,261

Version

1.4.2

License

GPL-2 | GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

John Mount

Last Published

January 19th, 2020

Functions in rquery (1.4.2)

apply_right_S4,ANY,rquery_db_info-method

Apply pipeline to a database.
affine_transform

Implement an affine transformaton
apply_right_S4,relop_arrow,relop_arrow-method

S4 dispatch method for apply_right.
build_join_plan

Build a join plan.
actualize_join_plan

Execute an ordered sequence of left joins.
arrow

Data arrow
apply_right.relop

Execute pipeline treating pipe_left_arg as local data to be copied into database.
apply_right_S4,data.frame,relop_arrow-method

S4 dispatch method for apply_right.
assign_slice

Assign a value to a slice of data (set of rows meeting a condition, and specified set of columns).
count_null_cols

Count NULLs per row for given column set.
db_td

Construct a table description from a database source.
inspect_join_plan

check that a join plan is consistent with table descriptions.
ex

Execute a wrapped execution pipeline.
if_else_op

Build a relop node simulating a per-row block-if(){}else{}.
example_employee_date

Build some example tables (requires DBI).
extend

Extend data by adding more columns.
columns_used

Return columns used
commencify

materialize_node

Create a materialize node.
extend_se

Extend data by adding more columns.
key_inspector_all_cols

Return all columns as guess of preferred primary keys.
graph_join_plan

Build a draw-able specification of the join diagram
if_else_block

Build a sequence of statements simulating an if/else block-if(){}else{}.
key_inspector_sqlite

Return all primary key columns as guess at preferred primary keys for a SQLite handle.
pre_sql_token

pre_sql_token
op_diagram

Build a diagram of a optree pipeline.
project

project data by grouping, and adding aggregate columns.
null_replace

Create a null_replace node.
materialize_sql

Materialize a user supplied SQL statement as a table.
describe_tables

Build a nice description of a table.
column_names

Return column names
drop_columns

Make a drop columns node (not a relational operation).
execute

Execute an operator tree, bringing back the result to memory.
local_td

Construct a table description of a local data.frame.
complete_design

Complete an experimental design.
project_se

project data by grouping, and adding aggregate columns.
mk_td

Make a table description directly.
key_inspector_postgresql

Return all primary key columns as guess at preferred primary keys for a PostgreSQL handle.
getDBOption

Get a database connection option.
convert_yaml_to_pipeline

Convert a series of simple objects (from YAML deserializaton) to an rquery pipeline.
format_node

Format a single node for printing.
lookup_by_column

Use one column to pick values from other columns.
expand_grid

Cross product vectors in database.
pre_sql_sub_expr

pre_sql_sub_expr
natural_join

Make a natural_join node.
order_expr

Make a order_expr node.
mark_null_cols

Indicate NULLs per row for given column set.
pre_sql_identifier

pre_sql_identifier: abstract name of a column and where it is comming from
quantile_node

Compute quantiles over non-NULL values (without interpolation, needs a database with window functions).
pre_sql_string

pre_sql_string
order_expr_se

Make a order_expr node.
quote_identifier

Quote an identifier.
order_rows

Make an orderby node (not a relational operation).
map_column_values

Remap values in a set of columns.
materialize

Materialize an optree as a table.
non_sql_node

Wrap a non-SQL node.
orderby

Make an orderby node (not a relational operation).
pre_sql_to_query

Return SQL transform of tokens.
rq_function_mappings

Return function mappings for a connection
rquery_default_methods

Default to_sql method implementations.
rq_execute

Execute a query, typically an update that is not supposed to return results.
pre_sql_to_query.pre_sql_sub_expr

Convert a pre_sql token object to SQL query text.
pre_sql_to_query.pre_sql_token

Convert a pre_sql token object to SQL query text.
quote_literal

Quote a value
rq_remove_table

Remove table
pick_top_k

Build an optree pipeline that selects up to the top k rows from each group in the given order.
rq_connection_tests

Try and test database for some option settings.
rq_copy_to

Copy local R table to remote data handle.
row_counts

Build an optree pipeline counts rows.
pre_sql_fn

pre_sql_token funtion name
rename_columns

Make a rename columns node (copies columns not renamed).
normalize_cols

Build an optree pipeline that normalizes a set of columns so each column sums to one in each partition.
rstr

Quick look at remote data
rq_table_exists

Check if a table exists.
quantile_cols

Compute quantiles of specified columns (without interpolation, needs a database with window functions).
setDBOption

Set a database connection option.
tables_used

Return vector of table names used.
setDBOpt

Set a database connection option.
quote_string

Quote a string
rq_nrow

Count rows and return as numeric
theta_join

Make a theta_join node.
rq_get_query

Execute a get query, typically a non-update that is supposed to return results.
rsummary

Compute usable summary of columns of remote table.
sql_node

Make a general SQL node.
rsummary_node

Create an rsumary relop operator node.
quote_table_name

Quote a table name.
reexports

Objects exported from other packages
rq_colnames

List table column names.
set_indicator

Make a set indicator node.
wrap

Wrap a data frame for later execution.
str_pre_sql_sub_expr

Structure of a pre_sql_sub_expr
unionall

Make an unionall node (not a relational operation).
select_rows_se

Make a select rows node.
rq_coltypes

Get column types by example values as a data.frame.
rquery

rquery: Relational Query Generator for Data Manipulation
topo_sort_tables

Topologically sort join plan so values are available before uses.
select_rows

Make a select rows node.
rquery_apply_to_data_frame

Execute optree in an environment where d is the only data.
rq_connection_advice

Get advice for a DB connection (beyond tests).
rq_connection_name

Build a canonical name for a db connection class.
theta_join_se

Make a theta_join node.
to_sql

Return SQL implementation of operation tree.
sql_expr_set

Build a query that applies a SQL expression to a set of columns.
run_rquery_tests

Run rquery package tests.
to_transport_representation

Convert an rquery op diagram to a simple representation, appropriate for conversion to YAML.
select_columns

Make a select columns node (not a relational operation).
tokenize_for_SQL

Cross-parse from an R parse tree into SQL.
rquery_default_db_info

An example rquery_db_info object useful for formatting SQL without a database connection.
rquery_db_info

Build a db information stand-in