glue custom knitr language engines

knitr::opts_chunk$set(echo = TRUE)

Glue provides a few custom language engines for knitr, which allows you to use glue directly in knitr chunks.

glue engine

The first engine is the glue engine, which evaluates the chunk contents as a glue template.

1 + 1 = {1 + 1}

Maybe the most useful use of the glue engine is to set the knitr option results = 'asis' and output markdown or HTML directly into the document.

`r '' ````{glue, results = 'asis', echo = FALSE}
#### mtcars has **{nrow(mtcars)} rows** and _{ncol(mtcars)} columns_.

```{glue, results = 'asis', echo = FALSE}

mtcars has {nrow(mtcars)} rows and {ncol(mtcars)} columns.

If you want to pass additional arguments into the glue call, simply include them as chunk options.

`r '' ````{glue, .open = "<<", .close = ">>", results = 'asis', echo = FALSE}
The **median waiting time** between eruptions is <<median(faithful$waiting)>>.
```{glue, .open = "<<", .close = ">>", results = 'asis', echo = FALSE}
The **median waiting time** between eruptions is <<median(faithful$waiting)>>.

## `glue_sql` engine

The second engine is `glue_sql`, which will use `glue::glue_sql()` to generate a SQL query and then run the query using the [sql engine](

First we create a new connection to an in-memory SQLite database, and write a new table to it.
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
mtcars$model <- rownames(mtcars)
DBI::dbWriteTable(con, "mtcars", mtcars)

Next define some variables we that we can use with glue to interpolate.
var <- "mpg"
tbl <- "mtcars"
num <- 150

Then we can use `glue_sql` to construct and run a query using those variables into that database. *Note* you need to provide the connection object as a `connection` chunk option.

In this example there are two type of quotes. The first is a bare backtick, these are passed directly to the SQL engine unchanged.
The second is backticks inside of braces, which are specially interpreted to do the proper quoting for the given SQL engine by glue.
In this example we use the `sqlite` engine, which uses backticks for quoting, but you would use the same backticks inside brace syntax for postgreSQL, and `glue_sql()` would automatically use double quotes for quoting instead.

`r '' ````{glue_sql, connection = con}
SELECT `model`, `hp`, {`var`}
FROM {`tbl`}
WHERE {`tbl`}.hp > {num}

{glue_sql, connection = con} SELECT `model`, `hp`, {`var`} FROM {`tbl`} WHERE {`tbl`}.hp > {num}

Try the glue package in your browser

Any scripts or data that you put into this service are public.

glue documentation built on March 18, 2022, 7:21 p.m.