Skip to content

Commit 793a2f3

Browse files
jennybchadley
andauthored
Polish README and introduction to glue (#337)
* Work on README * Work on "Get started" vignette * Was in the wrong place * Apply suggestions from code review Co-authored-by: Hadley Wickham <h.wickham@gmail.com> * Use function body example here too; rebuild README.md * Update vignettes/glue.Rmd Co-authored-by: Hadley Wickham <h.wickham@gmail.com> * Take the chance to talk about the glue class and printing * Add as.character() --------- Co-authored-by: Hadley Wickham <h.wickham@gmail.com>
1 parent 05e85e1 commit 793a2f3

File tree

3 files changed

+292
-332
lines changed

3 files changed

+292
-332
lines changed

README.Rmd

Lines changed: 50 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ library(glue)
2121
[![test-coverage](https://github.com/tidyverse/glue/actions/workflows/test-coverage.yaml/badge.svg)](https://github.com/tidyverse/glue/actions/workflows/test-coverage.yaml)
2222
<!-- badges: end -->
2323

24-
## Overview
25-
26-
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.
24+
glue offers interpreted string literals that are small, fast, and dependency-free.
25+
glue does this by embedding R expressions in curly braces, which are then evaluated and inserted into the string.
2726

2827
## Installation
2928

@@ -49,136 +48,87 @@ pak::pak("tidyverse/glue")
4948
library(glue)
5049
5150
name <- "Fred"
52-
glue('My name is {name}.')
53-
54-
# A literal brace is inserted by using doubled braces.
55-
name <- "Fred"
56-
glue("My name is {name}, not {{name}}.")
51+
glue("My name is {name}.")
5752
```
5853

59-
`glue::glue()` is also made available via `stringr::str_glue()`.
60-
So if you've already attached stringr (or perhaps the whole tidyverse), you can access `glue()` like so:
54+
`stringr::str_glue()` is an alias for `glue::glue()`.
55+
So if you've already attached stringr (or perhaps the whole tidyverse), you can use `str_glue()` to access all of the functionality of `glue()`:
6156

6257
```{r eval = FALSE}
6358
library(stringr) # or library(tidyverse)
6459
65-
stringr_fcn <- "`stringr::str_glue()`"
66-
glue_fcn <- "`glue::glue()`"
67-
68-
str_glue('{stringr_fcn} is essentially an alias for {glue_fcn}.')
69-
#> `stringr::str_glue()` is essentially an alias for `glue::glue()`.
60+
name <- "Wilma"
61+
str_glue("My name is {name}.")
62+
#> My name is Wilma.
7063
```
7164

72-
`glue_data()` works well with pipes:
65+
You're not limited to using a bare symbol inside `{}`; it can be any little bit of R code:
7366

7467
```{r}
75-
mtcars$model <- rownames(mtcars)
76-
mtcars |> head() |> glue_data("{model} has {hp} hp")
68+
name <- "Pebbles"
69+
glue("Here is my name in uppercase and doubled: {strrep(toupper(name), 2)}.")
7770
```
7871

79-
##### `glue_data()` is useful with [magrittr](https://cran.r-project.org/package=magrittr) pipes.
80-
```{r}
81-
`%>%` <- magrittr::`%>%`
82-
head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp")
83-
```
72+
### Data can come from various sources
8473

85-
##### `glue()` is useful within dplyr pipelines
86-
```{r, message = FALSE}
87-
library(dplyr)
88-
head(iris) %>%
89-
mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
90-
```
74+
glue can interpolate values from the local environment or from data passed in `name = value` form:
9175

92-
##### Leading whitespace and blank lines from the first and last lines are automatically trimmed.
93-
This lets you indent the strings naturally in code.
9476
```{r}
95-
glue("
96-
A formatted string
97-
Can have multiple lines
98-
with additional indention preserved
99-
")
77+
x <- "the local environment"
78+
glue(
79+
"`glue()` can access values from {x} or from {y}. {z}",
80+
y = "named arguments",
81+
z = "Woo!"
82+
)
10083
```
10184

102-
##### An additional newline can be used if you want a leading or trailing newline.
103-
```{r}
104-
glue("
105-
106-
leading or trailing newlines can be added explicitly
85+
If the relevant data lives in a data frame (or list or environment), use `glue_data()` instead:
10786

108-
")
109-
```
110-
111-
##### `\\` at the end of a line continues it without a new line.
11287
```{r}
113-
glue("
114-
A formatted string \\
115-
can also be on a \\
116-
single line
117-
")
88+
mini_mtcars <- head(cbind(model = rownames(mtcars), mtcars))
89+
glue_data(mini_mtcars, "{model} has {hp} hp.")
11890
```
11991

120-
##### A literal brace is inserted by using doubled braces.
121-
```{r}
122-
name <- "Fred"
123-
glue("My name is {name}, not {{name}}.")
124-
```
92+
`glue_data()` is very natural to use with the pipe:
12593

126-
##### Alternative delimiters can be specified with `.open` and `.close`.
12794
```{r}
128-
one <- "1"
129-
glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
95+
mini_mtcars |>
96+
glue_data("{model} gets {mpg} miles per gallon.")
13097
```
13198

132-
##### All valid R code works in expressions, including braces and escaping.
133-
Backslashes do need to be doubled just like in all R strings.
134-
```{r}
135-
`foo}\`` <- "foo"
136-
glue("{
137-
{
138-
'}\\'' # { and } in comments, single quotes
139-
\"}\\\"\" # or double quotes are ignored
140-
`foo}\\`` # as are { in backticks
141-
}
142-
}")
143-
```
99+
These `glue_data()` examples also demonstrate that `glue()` is vectorized over the data.
100+
101+
### What you see is awfully close to what you get
102+
103+
`glue()` lets you write code that makes it easy to predict what the final string will look like.
104+
There is considerably less syntactical noise and mystery compared to `paste()` and `sprintf()`.
144105

145-
##### `glue_sql()` makes constructing SQL statements safe and easy
146-
Use backticks to quote identifiers, normal strings and numbers are quoted
147-
appropriately for your backend.
106+
Empty first and last lines are automatically trimmed, as is leading whitespace that is common across all lines.
107+
You don't have to choose between indenting your code properly and getting the output you actually want.
108+
Consider what happens when `glue()` is used inside the body of a function:
148109

149110
```{r}
150-
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
151-
colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
152-
DBI::dbWriteTable(con, "iris", iris)
153-
154-
var <- "sepal_width"
155-
tbl <- "iris"
156-
num <- 2
157-
val <- "setosa"
158-
glue_sql("
159-
SELECT {`var`}
160-
FROM {`tbl`}
161-
WHERE {`tbl`}.sepal_length > {num}
162-
AND {`tbl`}.species = {val}
163-
", .con = con)
111+
foo <- function() {
112+
glue("
113+
A formatted string
114+
Can have multiple lines
115+
with additional indention preserved")
116+
}
117+
foo()
164118
```
165119

166-
# Other implementations
167-
168-
Some other implementations of string interpolation in R (although not using identical syntax).
120+
The leading whitespace that is common to all 3 lines is absent from the result.
169121

170-
- [stringr::str_interp](https://stringr.tidyverse.org/reference/str_interp.html)
171-
- [R.utils::gstring](https://cran.r-project.org/package=R.utils)
172-
- [rprintf](https://cran.r-project.org/package=rprintf)
122+
## Learning more
173123

174-
String templating is closely related to string interpolation, although not
175-
exactly the same concept. Some packages implementing string templating in R
176-
include.
124+
glue is a relatively small and focused package, but there's more to it than the basic usage of `glue()` and `glue_data()` shown here.
125+
More recommended functions and resources:
177126

178-
- [whisker](https://cran.r-project.org/package=whisker)
179-
- [brew](https://cran.r-project.org/package=brew)
180-
- [jinjar](https://cran.r-project.org/package=jinjar)
127+
* The "Get started" article (`vignette("glue")`) demonstrates more interesting features of `glue()` and `glue_data()`.
128+
* `glue_sql()` and `glue_data_sql()` are specialized functions for producing SQL statements.
129+
* glue provides a couple of custom knitr engines that allow you to use glue syntax in chunks; learn more in `vignette("engines", package = "glue")`.
181130

182131
## Code of Conduct
183132

184-
Please note that the glue project is released with a [Contributor Code of Conduct](https://glue.tidyverse.org/CODE_OF_CONDUCT.html). By contributing to this project, you agree to abide by its terms.
133+
Please note that this project is released with a [Contributor Code of Conduct](https://glue.tidyverse.org/CODE_OF_CONDUCT.html).
134+
By participating in this project, you agree to abide by its terms.

0 commit comments

Comments
 (0)