glue 1.2.0 is now available on CRAN! glue is designed to make it easy to interpolate (“glue”) your data into strings. Compared to equivalents like paste() and sprintf() it is easier to write and less time consuming to maintain. It also has no non-base dependencies so is easy to include in packages.

Install the latest version with:

glue has three primary functions, glue(), glue_data() and collapse(). glue() works in a similar way to double quotes " in a shell or python’s String Interpolation. You surround the code you want evaluated by {} and the value of the expression is inserted into the string.

glue is also vectorized over its inputs.

glue_data() works like glue(), but instead of looking up its variables from the calling environment it looks them up from the first argument (usually a data frame or tibble). This makes glue_data() very useful within pipe chains.

collapse() is used to combine multiple values into one. The last argument is used to change the separator for the last value.

glue transformers

New to glue 1.2.0 are transformer functions, which allow you to define custom behavior for glue functions. For example a collapse_transformer() which automatically collapses any blocks which end with *.

Or an sprintf transformer which lets you use sprintf style numeric formatting with glue.

sprintf_transformer <- function(code, envir) {
  m <- regexpr("%.+$", code)
  if (m != -1) {
    format <- regmatches(code, m)
    regmatches(code, m) <- ""
    res <- eval(parse(text = code), envir = envir), list(format, res))
  } else {
    eval(parse(text = code), envir = envir)

glue_fmt <- function(..., .envir = parent.frame()) {
  glue(..., .transformer = sprintf_transformer, .envir = .envir)
glue_fmt("π = {pi%.5f}")
#> π = 3.14159


Also new to glue 1.2.0 is glue_sql() and glue_data_sql(), which are helper functions defined with glue transformers to make it easy and safe to construct SQL statements.

Using glue_sql() values are automatically quoted appropriately and variables can be quoted with backticks.

Other changes

There are many other bug fixes and other minor improvements. You can see a complete list in the release notes.

A big thanks goes to all the community members who contributed code and opened issues since the last release! (@artemklevtsov, @daroczig, @DarwinAwardWinner, @edarague, @hadley, @hughjonesd, @jennybc, @jimhester, @jjchern, @klmr, @krlmlr, @lionel-, @mgirlich, @mmuurr, @npjc, @pssguy, and @robinsones)