Skip to contents

Combine strings, with text inside braces {} evaluated as R expressions to be output directly within the string.

Usage

str_glue(..., separator = "", environment = parent.frame())

Arguments

...

Expression strings to format and concatenate.

Named arguments are taken to be temporary variables available for substitution.

separator

A character string to separate the concatenated elements. Defaults to an empty string, which results in no separation between elements.

environment

An evironment object to evaluate the expression in. By default this is the environment str_glue() was called from.

Value

A character vector with same length as the longest input.

Details

Unnamed arguments to ... are taken as strings containing expressions to evaluate and format. Multiple inputs are concatenated together before being formatted. Named arguments will be added as variables to a temporary environment along with the variables supplied within environment.

Doubling the braces escapes them, for when you want braces in your output strings.

See also

str_concat() for simply combining strings and chr_collapse() for collapsing strings in character vectors to a single string.

sprintf() for C-style string formatting and variable interpolation.

Examples

x <- 5

# Evaluate R expressions in braces {} in the middle of a string
str_glue("The square of {x} is {x^2}")
#> [1] "The square of 5 is 25"
tri_num_str <- \(n) chr_collapse(cumsum(seq(n)), ", ")
str_glue("The first {x} triangle numbers are {tri_num_str(x)}.")
#> [1] "The first 5 triangle numbers are 1, 3, 6, 10, 15."

# Named arguments are taken as temporary variables.
str_glue(
   "My name is {name}, ",
   "I am {age} years old. ",
   "In {x} years I'll be {age + x}.",
   name = "John",
   age = 45
)
#> [1] "My name is John, I am 45 years old. In 5 years I'll be 50."