library(glue)
library(palmerpenguins) # I'm loading this to use its data later
Day 12: glue’s knitr engine
Use glue’s custom knitr language engine to evaluate chunk contents as a glue template.
If you’re unfamiliar with glue (Hester and Bryan 2022), let me catch you up to speed:
Glue offers interpreted string literals that are small, fast, and dependency-free. Glue does this by embedding R expressions in curly braces which are then evaluated and inserted into the argument string.
Basically, it lets you pass variables directly into strings by wrapping them in curly braces ({}
), making for some very reader-friendly string interpolation.
Today, I want to highlight a feature of glue that’s discussed less often: its custom knitr language engine1.
To use the glue engine in an R Markdown or Quarto document, you just need to load the glue library.
Once you’ve done that, you use it by using glue
as the named engine (as you would for any other language, say r
or python
in a code cell), and the contents will be evaluated as a glue template.
```{glue}
1 + 1 = {1 + 1}
```
1 + 1 = 2
You can output markdown or HTML directly into your document, by setting the option results
to 'asis'
.
```{glue}
#| results: 'asis'
`penguins` has **{nrow(penguins)} rows** and _{ncol(penguins)} columns_.
```
penguins
has 344 rows and 8 columns.
As you can see, the markdown formatting I’ve used in the chunk above is rendered in the output.
If you want to pass any arguments to your glue()
call, you can include them as chunk options. For example, let’s say I want to use something other than curly braces to surround my R expressions. I can set the opening and closing delimiters with the .open
and .close
arguments as options.
```{glue}
#| .open: "<<"
#| .close: ">>"
#| results: 'asis'
The **median waiting time** between eruptions is <<median(faithful$waiting)>>.
```
The median waiting time between eruptions is 76.
Learn more
The glue package has a whole vignette on its custom knitr language engines, including a section on the glue_sql
engine, which I haven’t covered here. For the rest of glue’s features, see the package documentation.