How to Use the str_glue() Function in R

The str_glue() function in R’s stringr package is “used to concatenate strings together, often using variables within the string.”


str_glue(..., .sep, .envir = parent.frame(), .x, .na = "NA")


  1. : These are the strings to be concatenated. Strings can be a mix of constants and expressions enclosed in {}. The expressions within {} will be evaluated, and their results will be inserted into the string.
  2. .sep: Separator used to separate elements.
  3. .envir: The environment in which to evaluate the expressions. The default is the parent frame.
  4. .x: It is an environment, list, or data frame used to look up values.
  5. .na: A character vector of length 1 to replace NA values. The default is “NA”.

Return value

It returns a character vector with the same length as the longest input.

Example 1: Simple String Concatenation


result <- str_glue("Hello", " ", "World!")



Hello World!

Example 2: Using Variables


name <- "John"
age <- 25

result <- str_glue("My name is {name} and I am {age} years old.")


My name is John and I am 25 years old.

Example 3: Handling NA Values


value <- NA
result <- str_glue("The value is {value}.", .na = "missing")


The value is missing.

Remember that the str_glue() function is handy when combined with data manipulation packages like dplyr, allowing you to create new variables in a data frame using string interpolation.

That’s it!

Related posts

str_detect() function in R

str_c() function in R

str_like() function in R

str() function in R

str_like() function in R

Leave a Comment