Created
March 16, 2020 12:45
-
-
Save BroVic/3ac5e9e858d4cc7e807f883b39b76037 to your computer and use it in GitHub Desktop.
Why would I want to use glue instead of base functions for string interpolation?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Why 'glue' and not 'paste' or 'sprintf' | |
# adapting the example | |
library(microbenchmark) | |
library(glue) | |
name <- "Fred" | |
age <- 30 | |
anniversary <- as.Date('1991-10-12') | |
t <- microbenchmark( | |
glue = glue( | |
'My name is {name},', | |
'my age next year is {age + 1}', | |
'my anniversary is {format(anniversary, "%A, %B %d, %Y")}.' | |
), | |
sprintf = sprintf( | |
'My name is %s, my age next year is %i, my anniversary is %s', | |
name, | |
age + 1, | |
format(anniversary, "%A, %B %d, %Y") | |
) | |
) | |
boxplot(t) | |
# pipes | |
library(magrittr) | |
t <- microbenchmark( | |
glue = mtcars %>% glue_data("{rownames(.)} has {hp} hp"), | |
sprintf = mtcars %>% { sprintf("%s has %i hp", rownames(.), .$hp) } | |
) | |
boxplot(t) | |
library(dplyr) | |
t <- microbenchmark( | |
glue = head(iris) %>% | |
mutate( | |
description = glue("This {Species} has a petal length of {Petal.Length}") | |
), | |
sprintf = head(iris) %>% | |
mutate( | |
description = sprintf("This %s has a petal length of %1f", Species, Petal.Length) | |
) | |
) | |
boxplot(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment