• Stars
    star
    685
  • Rank 63,334 (Top 2 %)
  • Language
    R
  • License
    Other
  • Created over 7 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Glue strings to data in R. Small, fast, dependency free interpreted string literals.

glue

CRAN_Status_Badge R-CMD-check test-coverage

Overview

Glue offers interpreted string literals that are small, fast, and dependency-free. Glue does this by embedding R expressions in curly braces which are then evaluated and inserted into the argument string.

Installation

# Install released version from CRAN
install.packages("glue")
# Install development version from GitHub
devtools::install_github("tidyverse/glue")

Usage

Variables can be passed directly into strings.
library(glue)
name <- "Fred"
glue('My name is {name}.')
#> My name is Fred.

Note that glue::glue() is also made available via stringr::str_glue(). So if you’ve already attached stringr (or perhaps the whole tidyverse), you can access glue() like so:

library(stringr) # or library(tidyverse)

stringr_fcn <- "`stringr::str_glue()`"
glue_fcn    <- "`glue::glue()`"

str_glue('{stringr_fcn} is essentially an alias for {glue_fcn}.')
#> `stringr::str_glue()` is essentially an alias for `glue::glue()`.
Long strings are broken by line and concatenated together.
library(glue)

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.
Named arguments are used to assign 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.
glue_data() is useful with magrittr pipes.
`%>%` <- magrittr::`%>%`
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
glue() is useful within dplyr pipelines
library(dplyr)
head(iris) %>%
  mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa
#>                             description
#> 1 This setosa has a petal length of 1.4
#> 2 This setosa has a petal length of 1.4
#> 3 This setosa has a petal length of 1.3
#> 4 This setosa has a petal length of 1.5
#> 5 This setosa has a petal length of 1.4
#> 6 This setosa has a petal length of 1.7
Leading whitespace and blank lines from the first and last lines are automatically trimmed.

This lets you indent the strings naturally in code.

glue("
    A formatted string
    Can have multiple lines
      with additional indention preserved
    ")
#> A formatted string
#> Can have multiple lines
#>   with additional indention preserved
An additional newline can be used if you want a leading or trailing newline.
glue("

  leading or trailing newlines can be added explicitly

  ")
#> 
#> leading or trailing newlines can be added explicitly
\\ at the end of a line continues it without a new line.
glue("
    A formatted string \\
    can also be on a \\
    single line
    ")
#> A formatted string can also be on a single line
A literal brace is inserted by using doubled braces.
name <- "Fred"
glue("My name is {name}, not {{name}}.")
#> My name is Fred, not {name}.
Alternative delimiters can be specified with .open and .close.
one <- "1"
glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
#> The value of $e^{2\pi i}$ is $1$.
All valid R code works in expressions, including braces and escaping.

Backslashes do need to be doubled just like in all R strings.

  `foo}\`` <- "foo"
glue("{
      {
        '}\\'' # { and } in comments, single quotes
        \"}\\\"\" # or double quotes are ignored
        `foo}\\`` # as are { in backticks
      }
  }")
#> foo
glue_sql() makes constructing SQL statements safe and easy

Use backticks to quote identifiers, normal strings and numbers are quoted appropriately for your backend.

library(glue)

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'

# `glue_sql()` can be used in conjunction with parameterized queries using
# `DBI::dbBind()` to provide protection for SQL Injection attacks
 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
DBI::dbClearResult(query)

# `glue_sql()` can be used to build up more complex queries with
# interchangeable sub queries. It returns `DBI::SQL()` objects which are
# properly protected from quoting.
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

# If you want to input multiple values for use in SQL IN statements put `*`
# at the end of the value and the values will be collapsed and quoted appropriately.
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')
Optionally combine strings with +
x <- 1
y <- 3
glue("x + y") + " = {x + y}"
#> x + y = 4

Other implementations

Some other implementations of string interpolation in R (although not using identical syntax).

String templating is closely related to string interpolation, although not exactly the same concept. Some packages implementing string templating in R include.

Code of Conduct

Please note that the glue project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

More Repositories

1

ggplot2

An implementation of the Grammar of Graphics in R
R
6,311
star
2

dplyr

dplyr: A grammar of data manipulation
R
4,627
star
3

tidyverse

Easily install and load packages from the tidyverse
R
1,575
star
4

rvest

Simple web scraping for R
R
1,455
star
5

tidyr

Tidy Messy Data
R
1,323
star
6

purrr

A functional programming toolkit for R
R
1,211
star
7

readr

Read flat files (csv, tsv, fwf) into R
R
985
star
8

magrittr

Improve the readability of R code with the pipe
R
952
star
9

datascience-box

Data Science Course in a Box
JavaScript
895
star
10

reprex

Render bits of R code for sharing, e.g., on GitHub or StackOverflow.
R
726
star
11

readxl

Read excel files (.xls and .xlsx) into R πŸ–‡
C++
713
star
12

lubridate

Make working with dates in R just that little bit easier
R
712
star
13

dtplyr

Data table backend for dplyr
R
656
star
14

tibble

A modern re-imagining of the data frame
R
641
star
15

multidplyr

A dplyr backend that partitions a data frame over multiple processes
R
636
star
16

vroom

Fast reading of delimited files
C++
604
star
17

stringr

A fresh approach to string manipulation in R
R
565
star
18

forcats

🐈🐈🐈🐈: tools for working with categorical variables (factors)
R
533
star
19

dbplyr

Database (DBI) backend for dplyr
R
455
star
20

haven

Read SPSS, Stata and SAS files from R
C
421
star
21

modelr

Helper functions for modelling
R
398
star
22

googlesheets4

Google Spreadsheets R API (reboot of the googlesheets package)
R
347
star
23

googledrive

Google Drive R API
R
312
star
24

style

The tidyverse style guide for R code
HTML
285
star
25

design

Tidyverse design principles
R
208
star
26

tidyverse.org

Source of tidyverse.org
HTML
186
star
27

hms

A simple class for storing time-of-day values
R
136
star
28

nycflights13

An R data package containing all out-bound flights from NYC in 2013 + useful metdata
R
121
star
29

tidyversedashboard

Tidyverse activity dashboard
R
71
star
30

tidy-dev-day

Tidyverse developer day
59
star
31

tidyeval

A guide to tidy evaluation
CSS
54
star
32

dsbox

Companion R package to Data Science Course in a Box
R
47
star
33

tidytemplate

A pkgdown template for core tidyverse packages
SCSS
45
star
34

blob

A simple S3 class for representing BLOBs
R
44
star
35

code-review

32
star
36

funs

Collection of low-level functions for working with vctrs
R
31
star
37

website-analytics

Web analytics for tidyverse + r-lib sites
R
28
star
38

tidyups

20
star
39

ggplot2-docs

ggplot2 documentation. Auto-generated from ggplot2 sources by pkgdown
HTML
10
star