-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathtransformers.Rmd
More file actions
236 lines (188 loc) · 6.5 KB
/
transformers.Rmd
File metadata and controls
236 lines (188 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
---
title: "Transformers"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Transformers}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
Transformers allow you to apply functions to the glue input and output, before
and after evaluation. This allows you to write things like `glue_sql()`, which
automatically quotes variables for you or add a syntax for automatically
collapsing outputs.
The transformer functions simply take two arguments `text` and `envir`, where
`text` is the unparsed string inside the glue block and `envir` is the
execution environment. Most transformers will then call `eval(parse(text = text,
keep.source = FALSE), envir)` which parses and evaluates the code.
You can then supply the transformer function to glue with the `.transformer`
argument. In this way users can manipulate the text before parsing and
change the output after evaluation.
It is often useful to write a `glue()` wrapper function which supplies a
`.transformer` to `glue()` or `glue_data()` and potentially has additional
arguments. One important consideration when doing this is to include
`.envir = parent.frame()` in the wrapper to ensure the evaluation environment
is correct.
Some example implementations of potentially useful transformers follow. The
aim right now is not to include most of these custom functions within the
`glue` package. Rather, users are encouraged to create custom functions using
transformers to fit their individual needs.
```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```
```{r}
library(glue)
```
### collapse transformer
A transformer which automatically collapses any glue block ending with `*`.
```{r}
collapse_transformer <- function(regex = "[*]$", ...) {
function(text, envir) {
collapse <- grepl(regex, text)
if (collapse) {
text <- sub(regex, "", text)
}
res <- identity_transformer(text, envir)
if (collapse) {
glue_collapse(res, ...)
} else {
res
}
}
}
glue("{1:5*}\n{letters[1:5]*}", .transformer = collapse_transformer(sep = ", "))
glue("{1:5*}\n{letters[1:5]*}", .transformer = collapse_transformer(sep = ", ", last = " and "))
x <- c("one", "two")
glue("{x}: {1:5*}", .transformer = collapse_transformer(sep = ", "))
```
### Shell quoting transformer
A transformer which automatically quotes variables for use in shell commands,
e.g. via `system()` or `system2()`.
```{r}
shell_transformer <- function(type = c("sh", "csh", "cmd", "cmd2")) {
type <- match.arg(type)
function(text, envir) {
res <- identity_transformer(text, envir)
shQuote(res)
}
}
glue_sh <- function(..., .envir = parent.frame(), .type = c("sh", "csh", "cmd", "cmd2")) {
.type <- match.arg(.type)
glue(..., .envir = .envir, .transformer = shell_transformer(.type))
}
filename <- "test"
writeLines(con = filename, "hello!")
command <- glue_sh("cat {filename}")
command
system(command)
```
```{r include = FALSE}
if (file.exists("test")) {
unlink("test")
}
```
### emoji transformer
A transformer which converts the text to the equivalent emoji.
```{r, eval = require("emo")}
emoji_transformer <- function(text, envir) {
if (grepl("[*]$", text)) {
text <- sub("[*]$", "", text)
glue_collapse(ji_find(text)$emoji)
} else {
ji(text)
}
}
glue_ji <- function(..., .envir = parent.frame()) {
glue(..., .open = ":", .close = ":", .envir = .envir, .transformer = emoji_transformer)
}
glue_ji("one :heart:")
glue_ji("many :heart*:")
```
### sprintf transformer
A transformer which allows succinct `sprintf` format strings.
```{r}
sprintf_transformer <- function(text, envir) {
m <- regexpr(":.+$", text)
if (m != -1) {
format <- substring(regmatches(text, m), 2)
regmatches(text, m) <- ""
res <- identity_transformer(text, envir)
do.call(sprintf, list(glue("%{format}"), res))
} else {
identity_transformer(text, envir)
}
}
glue_fmt <- function(..., .envir = parent.frame()) {
glue(..., .transformer = sprintf_transformer, .envir = .envir)
}
glue_fmt("π = {pi:.3f}")
```
### signif transformer
A transformer generator that represents numbers with a given number of significant digits.
This is useful if we want to represent all numbers using the same significant digits
```{r}
signif_transformer <- function(digits = 3) {
force(digits)
function(text, envir) {
x <- identity_transformer(text, envir)
if (is.numeric(x)) {
signif(x, digits = digits)
} else {
x
}
}
}
glue_signif <- function(..., .envir = parent.frame()) {
glue(..., .transformer = signif_transformer(3), .envir = .envir)
}
glue_signif("π = {pi}; 10π = {10*pi}; 100π = {100*pi}")
```
### safely transformer
A transformer that acts like `purrr::safely()`, which returns a value instead of an error.
```{r}
safely_transformer <- function(otherwise = NA) {
function(text, envir) {
tryCatch(
identity_transformer(text, envir),
error = function(e) if (is.language(otherwise)) eval(otherwise) else otherwise)
}
}
glue_safely <- function(..., .otherwise = NA, .envir = parent.frame()) {
glue(..., .transformer = safely_transformer(.otherwise), .envir = .envir)
}
# Default returns missing if there is an error
glue_safely("foo: {xyz}")
# Or an empty string
glue_safely("foo: {xyz}", .otherwise = "Error")
# Or output the error message in red
library(crayon)
glue_safely("foo: {xyz}", .otherwise = quote(glue("{red}Error: {conditionMessage(e)}{reset}")))
```
### "Variables and Values" transformer
A transformer that expands input of the form `{var_name=}` into `var_name = var_value`, i.e. a shorthand for exposing variable names with their values. This is inspired by an [f-strings feature coming in Python 3.8](https://docs.python.org/3.8/whatsnew/3.8.html#f-strings-now-support-for-quick-and-easy-debugging). It's actually more general: you can use it with an expression input such as `{expr=}`.
```{r}
vv_transformer <- function(text, envir) {
regex <- "=$"
if (!grepl(regex, text)) {
return(identity_transformer(text, envir))
}
text <- sub(regex, "", text)
res <- identity_transformer(text, envir)
n <- length(res)
res <- glue_collapse(res, sep = ", ")
if (n > 1) {
res <- c("[", res, "]")
}
glue_collapse(c(text, " = ", res))
}
```
```{r}
set.seed(1234)
description <- "some random"
numbers <- sample(100, 4)
average <- mean(numbers)
sum <- sum(numbers)
glue("For {description} {numbers=}, {average=}, {sum=}.", .transformer = vv_transformer)
a <- 3
b <- 5.6
glue("{a=}\n{b=}\n{a * 9 + b * 2=}", .transformer = vv_transformer)
```