preface
Today we want to introducetidyverse
Packages that format strings in:glue
glue
Provides lightweight, fast, and dependency free interpretable strings,glue
By willR
The expression is embedded in curly braces, then evaluated and inserted into the string.
install
install.packages("glue")
# or
install.packages("glue")
# install.packages("devtools")
devtools::install_github("tidyverse/glue")
use
1. Import
library(glue)
2. Simple use
Pass the variable directly into the string
> name <- "Fred"
> glue('My name is {name}.')
My name is Fred.
By placing the variable name between a pair of curly braces,glue
The variable name is replaced with the corresponding value
Strings can be written in multiple lines, and these lines are automatically connected in the end
> name <- "Fred"
> age <- 50
> anniversary <- as.Date("1991-10-12")
> glue('My name is {name},',
+ ' my age next year is {age + 1},',
+ ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.')
My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991
stayglue
Use named parameters in to specify temporary variables
> glue('My name is {name},',
+ ' my age next year is {age + 1},',
+ ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.',
+ name = "Joe",
+ age = 40,
+ anniversary = as.Date("2001-10-12"))
My name is Joe, my age next year is 41, my anniversary is Friday, October 12, 2001
3. glue_ Data with pipe character
glue_data()
It is very useful to match pipe characters
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
> head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp")
Mazda RX4 has 110 hp
Mazda RX4 Wag has 110 hp
Datsun 710 has 93 hp
Hornet 4 Drive has 110 hp
Hornet Sportabout has 175 hp
Valiant has 105 hp
Can also matchdplyr
use
> head(iris) %>%
+ mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species description
1 5.1 3.5 1.4 0.2 setosa This setosa has a petal length of 1.4
2 4.9 3.0 1.4 0.2 setosa This setosa has a petal length of 1.4
3 4.7 3.2 1.3 0.2 setosa This setosa has a petal length of 1.3
4 4.6 3.1 1.5 0.2 setosa This setosa has a petal length of 1.5
5 5.0 3.6 1.4 0.2 setosa This setosa has a petal length of 1.4
6 5.4 3.9 1.7 0.4 setosa This setosa has a petal length of 1.7
4. String
Leading spaces and line breaks on the first and last lines are automatically trimmed
> glue("
+ A formatted string
+ Can have multiple lines
+ with additional indention preserved
+ ")
A formatted string
Can have multiple lines
with additional indention preserved
You can add an extra newline character to the first or last line to achieve a blank line
> glue("
+
+ leading or trailing newlines can be added explicitly
+
+ ")
leading or trailing newlines can be added explicitly
Use at end of line\\
You can merge two rows
> glue("
+ A formatted string \\
+ can also be on a \\
+ single line
+ ")
A formatted string can also be on a single line
If you want to use curly braces in a string, you need to use double curly braces
> name <- "Fred"
> glue("My name is {name}, not {{name}}.")
My name is Fred, not {name}.
be careful: please compare the following differences
> a <- "foo"
> glue("{{a}}")
{a}
> glue("{{a} }")
{a} }
> glue("{ {a} }")
foo
> glue("{
+ a
+ }")
foo
> glue("{
+ {a}
+ }")
foo
> glue("{
+ {a}}")
foo
Double curly braces need to be used together
have access to+
Connection string
> x <- 1
> y <- 3
> glue("x + y") + " = {x + y}"
x + y = 4
5. Specify separator
glue
By default, the characters between curly braces are used as variable names or expressions. We can set.open
Andclose
Parameter to specify the delimiter
> one <- "1"
> glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
The value of $e^{2\pi i}$ is $1$.
6. SQL statement
glue
It also providesglue_sql
Function for formattingSQL
Statement, for example
> con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
> colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
> DBI::dbWriteTable(con, "iris", iris)
> var <- "sepal_width"
> tbl <- "iris"
> num <- 2
> val <- "setosa"
> glue_sql("
+ SELECT {`var`}
+ FROM {`tbl`}
+ WHERE {`tbl`}.sepal_length > {num}
+ AND {`tbl`}.species = {val}
+ ", .con = con)
<SQL> SELECT `sepal_width`
FROM `iris`
WHERE `iris`.sepal_length > 2
AND `iris`.species = 'setosa'
Can also cooperateDBI::dbBind()
Perform parametric query
> sql <- glue_sql("
+ SELECT {`var`}
+ FROM {`tbl`}
+ WHERE {`tbl`}.sepal_length > ?
+ ", .con = con)
> query <- DBI::dbSendQuery(con, sql)
> DBI::dbBind(query, list(num))
> DBI::dbFetch(query, n = 4)
sepal_width
1 3.5
2 3.0
3 3.2
4 3.1
It also supports more complex queries, such as proportional nested subqueries
> sub_query <- glue_sql("
+ SELECT *
+ FROM {`tbl`}
+ ", .con = con)
>
> glue_sql("
+ SELECT s.{`var`}
+ FROM ({sub_query}) AS s
+ ", .con = con)
<SQL> SELECT s.`sepal_width`
FROM (SELECT *
FROM `iris`) AS s
You can alsoIN
Add after declaration*
To accept multiple values
> glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
+ vals = 1, .con = con)
<SQL> SELECT * FROM `iris` WHERE sepal_length IN (1)
> glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
+ vals = 1:5, .con = con)
<SQL> SELECT * FROM `iris` WHERE sepal_length IN (1, 2, 3, 4, 5)
> glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
+ vals = "setosa", .con = con)
<SQL> SELECT * FROM `iris` WHERE species IN ('setosa')
> glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
+ vals = c("setosa", "versicolor"), .con = con)
<SQL> SELECT * FROM `iris` WHERE species IN ('setosa', 'versicolor')
7. Folding of string vector
have access toglue_collapse
Collapse a string vector of any length into a string vector of length 1
glue_collapse(x, sep = "", width = Inf, last = "")
-
x
: String vector -
sep
: a string used to separate elements in a vector -
width
: add after folding...
Maximum length after, -
last
: ifx
At least2
A string used to separate the last two elements
> glue_collapse(glue("{1:10}"))
12345678910
> glue_collapse(glue("{1:10}"), width = 7)
1234...
> glue_collapse(1:4, ", ", last = " and ")
1, 2, 3 and 4
8. Reference of single element
The following three functions that refer to a single element can be combinedglue_collapse
use
-
single_quote(x)
: wrap string elements in single quotes -
double_quote(x)
: wrap string elements in double quotes -
backtick(x)
: wrap string elements in backquotes
> glue('Values of x: {glue_collapse(backtick(x), sep = ", ", last = " and ")}')
Values of x: `1`, `2`, `3`, `4` and `5`
> glue('Values of x: {glue_collapse(single_quote(x), sep = ", ", last = " and ")}')
Values of x: '1', '2', '3', '4' and '5'
> glue('Values of x: {glue_collapse(double_quote(x), sep = ", ", last = " and ")}')
Values of x: "1", "2", "3", "4" and "5"
9. Color the output
glue
Can matchcrayon
Package defines some functions for terminal output coloring to color our output text
Import firstcrayon
> require(crayon)
glue
Providedglue_col()
andglue_data_col()
Two coloring functions

We can set black characters on a white background
> white_on_grey <- bgBlack $ white
> glue_col("{white_on_grey
+ Roses are {red {colors()[[552]]}}
+ Violets are {blue {colors()[[26]]}}
+ `glue_col()` can show {red c}{yellow o}{green l}{cyan o}{blue r}{magenta s}
+ and {bold bold} and {underline underline} too!
+ }")
