knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" ) library(glue)
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.
::: .pkgdown-release
# Install released version from CRAN install.packages("glue")
:::
::: .pkgdown-devel
# Install development version from GitHub pak::pak("tidyverse/glue")
:::
library(glue) name <- "Fred" glue('My name is {name}.')
Note that glue::glue()
is also made available via stringr::str_glue()
.
So if you've already attached stringr (or perhaps the whole tidyverse), you can access glue()
like so:
library(stringr) # or library(tidyverse) stringr_fcn <- "`stringr::str_glue()`" glue_fcn <- "`glue::glue()`" str_glue('{stringr_fcn} is essentially an alias for {glue_fcn}.') #> `stringr::str_glue()` is essentially an alias for `glue::glue()`.
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")}.')
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"))
glue_data()
is useful with magrittr pipes.`%>%` <- magrittr::`%>%` head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp")
glue()
is useful within dplyr pipelineslibrary(dplyr) head(iris) %>% mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
This lets you indent the strings naturally in code.
glue(" A formatted string Can have multiple lines with additional indention preserved ")
glue(" 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 ")
name <- "Fred" glue("My name is {name}, not {{name}}.")
.open
and .close
.one <- "1" glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
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 } }")
glue_sql()
makes constructing SQL statements safe and easyUse 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) # `glue_sql()` can be used in conjunction 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) 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) # 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) glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})", vals = 1:5, .con = con) glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})", vals = "setosa", .con = con) glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})", vals = c("setosa", "versicolor"), .con = con)
Some other implementations of string interpolation in R (although not using identical syntax).
String templating is closely related to string interpolation, although not exactly the same concept. Some packages implementing string templating in R include.
Please note that the glue project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.