6.5 Glue Strings Together
20180729 The glue (Hester and Bryan 2026) package provides a mechanism for building output strings from a collection of strings and variables. The basic use of glue::glue() will concatenate its string arguments with variable substitution identified using curly braces. In this exmaple we use the rattle::weatherAUS and format large numbers using scales::comma().
dsname <- "weatherAUS"
nobs <- nrow(weatherAUS)
starts <- min(weatherAUS$Date)
glue("The {dsname} dataset",
" has just less than {comma(nobs + 1)} observations,",
" starting from {format(starts, '%-d %B %Y')}.")## The weatherAUS dataset has just less than 275,411 observations, starting from 1 November 2007.
We can manually wrap the sentence.
glue("
The {dsname} dataset has just
less than {comma(nobs + 1)} observations
starting from {format(starts, '%-d %B %Y')}.
")## The weatherAUS dataset has just
## less than 275,411 observations
## starting from 1 November 2007.
Notice how the initial and last empty lines are handled ``as expected’’, and the line split is maintained.
Named arguments within the function call can be used to assign values to variables that only exist in the scope of the function call.
glue("
The {dsname} dataset has just
less than {comma(nobs + 1)} observations
starting from {format(starts, '%-d %B %Y')}.
",
dsname = "weather",
nobs = nrow(weather),
starts = min(weather$Date))## The weather dataset has just
## less than 367 observations
## starting from 1 July 2023.
We can also see the effect of indenting lines in this example, where the indentation is retained.
References
Hester, Jim, and Jennifer Bryan. 2026. Glue: Interpreted String Literals. https://glue.tidyverse.org/.
If you find this curated material useful then you can consider a donation to support it's ongoing availability and give you access to the PDF version of this book. The material has been scoped up by Generative AI without permission or any kind of recompense so do consider a donation if you can afford it. Unlike Generative AI your access to this materials is freely given. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Togaware has a 30 year tradition of making popular open source software which includes sold privacy preserving productivity apps, rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0