Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: a start to a getting started vignette #170

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 15 additions & 138 deletions README.Rmd
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
---
output:
github_document:
html_preview: false
output: github_document
---

<!-- README.md is generated from README.Rmd. Please edit that file -->
Expand Down Expand Up @@ -45,14 +43,20 @@ devtools::install_github("tidyverse/glue")

## Usage

##### Variables can be passed directly into strings.
`glue()` makes it easy to interpolate data into strings:

```{r}
library(glue)

name <- "Fred"
glue('My name is {name}.')

# A literal brace is inserted by using doubled braces.
name <- "Fred"
glue("My name is {name}, not {{name}}.")
```

Note that `glue::glue()` is also made available via `stringr::str_glue()`.
`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:

```{r eval = FALSE}
Expand All @@ -65,104 +69,22 @@ 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.
```{r}
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")}.')
```

##### Named arguments are used to assign temporary variables.
```{r}
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"))
```

##### `glue_data()` is useful with [magrittr](https://cran.r-project.org/package=magrittr) pipes.
```{r}
`%>%` <- magrittr::`%>%`
head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp")
```

##### Or within dplyr pipelines
```{r, message = FALSE}
library(dplyr)
head(iris) %>%
mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
```

##### Leading whitespace and blank lines from the first and last lines are automatically trimmed.
This lets you indent the strings naturally in code.
```{r}
glue("
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.
```{r}
glue("

leading or trailing newlines can be added explicitly

")
```

##### `\\` at the end of a line continues it without a new line.
```{r}
glue("
A formatted string \\
can also be on a \\
single line
")
```

##### A literal brace is inserted by using doubled braces.
```{r}
name <- "Fred"
glue("My name is {name}, not {{name}}.")
```
`glue_data()` works well with pipes:

##### Alternative delimiters can be specified with `.open` and `.close`.
```{r}
one <- "1"
glue("The value of $e^{2\\pi i}$ is $<<one>>$.", .open = "<<", .close = ">>")
mtcars$model <- rownames(mtcars)
mtcars |> head() |> glue_data("{model} has {hp} hp")
```

##### All valid R code works in expressions, including braces and escaping.
Backslashes do need to be doubled just like in all R strings.
```{r}
`foo}\`` <- "foo"
glue("{
{
'}\\'' # { and } in comments, single quotes
\"}\\\"\" # or double quotes are ignored
`foo}\\`` # as are { in backticks
}
}")
```

##### `glue_sql()` makes constructing SQL statements safe and easy
`glue_sql()` makes constructing SQL statements safe and easy.
Use backticks to quote identifiers, normal strings and numbers are quoted
appropriately for your backend.

```{r}
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
Expand All @@ -173,54 +95,9 @@ glue_sql("
WHERE {`tbl`}.sepal_length > {num}
AND {`tbl`}.species = {val}
", .con = con)

# `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)
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)

# 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)

glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
vals = 1:5, .con = con)

glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
vals = "setosa", .con = con)

glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
vals = c("setosa", "versicolor"), .con = con)
```

##### Optionally combine strings with `+`

```{r}
x <- 1
y <- 3
glue("x + y") + " = {x + y}"
```
Learn more in `vignette("glue")`.

# Other implementations

Expand Down
Loading