String interpolation
glue2.RdExpressions enclosed by delimiters will be evaluated or extracted and inserted into the string.
Usage
glue2(
...,
.env = parent.frame(),
.open = "{",
.close = "}",
.sep = " ",
.eval = TRUE
)Arguments
- ...
(character)
One or more strings or character vectors to format. All inputs are coerced withas.character()and joined with.sepinto a single template string.- .env
(environment, list, or data.frame:
base::parent.frame())
The object used to evaluate expressions or get named values.- .open, .close
(one-character string:
"{"and"}")
The opening and closing delimiters of the expressions.- .sep
(string:
" ")
The separator used for concatenating strings in...- .eval
(Scalar logical:
c(TRUE, FALSE))
IfTRUE(default), the expressions in...are treated as R code and evaluated. IfFALSE, expressions in...will be treated as variable names in.env(this is faster than evaluation).
References
https://github.com/tidyverse/glue/blob/main/R/glue.R
https://github.com/coolbutuseless/gluestick/blob/main/R/gluestick.R
Examples
#----------------------------------------------------------------------------
# glue2() examples
#----------------------------------------------------------------------------
library(bkbase)
# Extract value from data object
data <- list(name = "Fred")
glue2("Hello {name}", .env = data)
#> [1] "Hello Fred"
# Extract value from parent.frame()
name <- "Fred"
glue2("Hello {name}")
#> [1] "Hello Fred"
# A vector is returned if expressions contain vectors
glue2("Number {1:2}")
#> [1] "Number 1" "Number 2"
# Evaluate expression
year_current <- as.numeric(format(Sys.Date(),'%Y'))
year_past <- 1970
glue2(
"Today is {Sys.Date()}",
"and it has been {year_current - year_past} years since 1970.",
.eval = TRUE
)
#> [1] "Today is 2026-06-14 and it has been 56 years since 1970."