Day 2: glue

Welcome back for the second day of the #packagecalendar, today we will be talking about the little package called glue package by Jim Hester.

the package is available from CRAN and can be downloaded with

install.packages("glue")

glue provides a way to do simple string interpretation using a simple syntax. The user can pass expressions into the string to be evaluated. This approach will feel similar to sprintf() expect that glue() shows the location in place. Simply pass any expression into the string by wrapping it in curly brackets ({}). glue() will vectorize when needed.

library(glue)

color <- "red"
glue("Santa packed a {color} present")
## Santa packed a red present

color <- c("red", "blue", "green")
glue("Santa packed a {color} present")
## Santa packed a red present
## Santa packed a blue present
## Santa packed a green present

This is commonly done by passing in a defined variable outside glue(), but remember that any expression can be passed to glue().

glue("`mtcars` has {nrow(mtcars)} rows and {ncol(mtcars)} columns")
## `mtcars` has 32 rows and 11 columns

The curly brackets might be used for something else depending on what you are trying to do. In that case, you can use the arguments .open and .close to redefine the borders.

n <- 1000000000 # number of children
glue("Santa uses the formula $<<n>>^{magic + love}$ to determine how much sugar to give to the elfs.",
     .open = "<<", .close = ">>")
## Santa uses the formula $1e+09^{magic + love}$ to determine how much sugar to give to the elfs.

There are many other use cases for glue, but I would like to highlight glue_data(). This function allows you to access variables inside a given data.frame, much the same way you can with many of the tidyverse packages.

For this example, I have created a summarized dataset.

library(dplyr)
mtcars_summarized <- mtcars %>%
  group_by(cyl) %>%
  summarise(n = n(),
            min_wt = min(wt),
            max_wt = max(wt)) %>%
  mutate_all(round, digits = 2)

We can then use glue_data() to create a little summary in text

cat("`mtcars` has\n")
glue_data(mtcars_summarized,
          "{n} cars with {cyl} cylinders, with a weight range of {min_wt*1000}-{max_wt*1000} lbs")
## `mtcars` has
## 11 cars with 4 cylinders, with a weight range of 1510-3190 lbs
## 7 cars with 6 cylinders, with a weight range of 2620-3460 lbs
## 14 cars with 8 cylinders, with a weight range of 3170-5420 lbs

This is all I have for today! Stay happy and I look forward to seeing you back tomorrow!

Additional resources