Interpreted String Literals

An implementation of interpreted string literals, inspired by Python's Literal String Interpolation < https://www.python.org/dev/peps/pep-0498/> and Docstrings < https://www.python.org/dev/peps/pep-0257/> and Julia's Triple-Quoted String Literals < https://docs.julialang.org/en/stable/manual/strings/#triple-quoted-string-literals>.


CRAN_Status_Badge Travis-CI Build Status Coverage Status AppVeyor Build Status

Glue strings to data in R. Small, fast, dependency free interpreted string literals.

Installation

devtools::install_github("tidyverse/glue")

Usage

Long strings are broken by line and concatenated together.
library(glue)
 
name <- "Fred"
age <- 50
anniversary <- as.Date("1991-10-12")
glue('My name is {name},',
  ' my age next year is {age + 1},',
  ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.')
#> My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.
Named arguments are used to assign temporary variables.
glue('My name is {name},',
  ' my age next year is {age + 1},',
  ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.',
  name = "Joe",
  age = 40,
  anniversary = as.Date("2001-10-12"))
#> My name is Joe, my age next year is 41, my anniversary is Friday, October 12, 2001.
glue_data() is useful with magrittr pipes.
`%>%` <- magrittr::`%>%`
head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp")
#> Mazda RX4 has 110 hp
#> Mazda RX4 Wag has 110 hp
#> Datsun 710 has 93 hp
#> Hornet 4 Drive has 110 hp
#> Hornet Sportabout has 175 hp
#> Valiant has 105 hp
Leading whitespace and blank lines from the first and last lines are automatically trimmed.

This lets you indent the strings naturally in code.

glue("
    A formatted string
    Can have multiple lines
      with additional indention preserved
    ")
#> A formatted string
#> Can have multiple lines
#>   with additional indention preserved
An additional newline can be used if you want a leading or trailing newline.
glue("
 
  leading or trailing newlines can be added explicitly
 
  ")
#> 
#> leading or trailing newlines can be added explicitly
\\ at the end of a line continues it without a new line.
glue("
    A formatted string \\
    can also be on a \\
    single line
    ")
#> A formatted string can also be on a single line
A literal brace is inserted by using doubled braces.
name <- "Fred"
glue("My name is {name}, not {{name}}.")
#> My name is Fred, not {name}.
Alternative delimiters can be specified with .open and .close.
one <- "1"
glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
#> The value of $e^{2\pi i}$ is $1$.
All valid R code works in expressions, including braces and escaping.

Backslashes do need to be doubled just like in all R strings.

  `foo}\`` <- "foo"
glue("{
      {
        '}\\'' # { and } in comments, single quotes
        \"}\\\"\" # or double quotes are ignored
        `foo}\\`` # as are { in backticks
      }
  }")
#> foo
glue_sql() makes constructing SQL statements safe and easy

Use backticks to quote identifiers, normal strings and numbers are quoted appropriately for your backend.

library(glue)
 
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris)
var <- "sepal_width"
tbl <- "iris"
num <- 2
val <- "setosa"
glue_sql("
  SELECT {`var`}
  FROM {`tbl`}
  WHERE {`tbl`}.sepal_length > {num}
    AND {`tbl`}.species = {val}
  ", .con = con)
#> <SQL> SELECT `sepal_width`
#> FROM `iris`
#> WHERE `iris`.sepal_length > 2
#>   AND `iris`.species = 'setosa'
 
# `glue_sql()` can be used in conjuction with parameterized queries using
# `DBI::dbBind()` to provide protection for SQL Injection attacks
 sql <- glue_sql("
    SELECT {`var`}
    FROM {`tbl`}
    WHERE {`tbl`}.sepal_length > ?
  ", .con = con)
query <- DBI::dbSendQuery(con, sql)
DBI::dbBind(query, list(num))
DBI::dbFetch(query, n = 4)
#>   sepal_width
#> 1         3.5
#> 2         3.0
#> 3         3.2
#> 4         3.1
DBI::dbClearResult(query)
 
# `glue_sql()` can be used to build up more complex queries with
# interchangeable sub queries. It returns `DBI::SQL()` objects which are
# properly protected from quoting.
sub_query <- glue_sql("
  SELECT *
  FROM {`tbl`}
  ", .con = con)
 
glue_sql("
  SELECT s.{`var`}
  FROM ({sub_query}) AS s
  ", .con = con)
#> <SQL> SELECT s.`sepal_width`
#> FROM (SELECT *
#> FROM `iris`) AS s
 
# If you want to input multiple values for use in SQL IN statements put `*`
# at the end of the value and the values will be collapsed and quoted appropriately.
glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
  vals = 1, .con = con)
#> <SQL> SELECT * FROM `iris` WHERE sepal_length IN (1)
 
glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
  vals = 1:5, .con = con)
#> <SQL> SELECT * FROM `iris` WHERE sepal_length IN (1, 2, 3, 4, 5)
 
glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
  vals = "setosa", .con = con)
#> <SQL> SELECT * FROM `iris` WHERE species IN ('setosa')
 
glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
  vals = c("setosa", "versicolor"), .con = con)
#> <SQL> SELECT * FROM `iris` WHERE species IN ('setosa', 'versicolor')

Other implementations

Some other implementations of string interpolation in R (although not using identical syntax).

News

glue 1.2.0

  • The implementation has been tweaked to be slightly faster in most cases.

  • glue() now has a .transformer argument, which allows you to use custom logic on how to evaluate the code within glue blocks. See vignettes("transformers") for more details and example transformer functions.

  • glue() now returns NA if any of the results are NA and .na is NULL. Otherwise NA values are replaced by the value of .na.

  • trim() to use the trimming logic from glue is now exported.

  • glue_sql() and glue_data_sql() functions added to make constructing SQL statements with glue safer and easier.

  • glue() is now easier to use when used within helper functions such as lapply.

  • Fix when last expression in glue() is NULL.

glue 1.1.1

  • Another fix for PROTECT / REPROTECT found by the rchk static analyzer.

glue 1.1.0

  • Fix for PROTECT errors when resizing output strings.

  • glue() always returns 'UTF-8' strings, converting inputs if in other encodings if needed.

  • to() and to_data() have been removed.

  • glue() and glue_data() can now take alternative delimiters to { and }. This is useful if you are writing to a format that uses a lot of braces, such as LaTeX. (#23)

  • collapse() now returns 0 length output if given 0 length input (#28).

glue 0.0.0.9000

  • Fix glue() to admit . as an embedded expression in a string (#15, @egnha).

  • Added a NEWS.md file to track changes to the package.

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.