6.5 Glue Strings Together

20180729 The glue (Hester and Bryan 2022) 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 226,869 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 226,869 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 November 2007.

We can also see the effect of indenting lines in this example, where the indentation is retained.

References

Hester, Jim, and Jennifer Bryan. 2022. Glue: Interpreted String Literals. https://CRAN.R-project.org/package=glue.


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes 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