Skip to contents

Expressions 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 with as.character() and joined with .sep into 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))
If TRUE (default), the expressions in ... are treated as R code and evaluated. If FALSE, expressions in ... will be treated as variable names in .env (this is faster than evaluation).

Value

Character vector

See also

Author

This function was modified from code by Posit (MIT license) and Mike Cheng (MIT license)

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."