generated from r4ds/bookclub-template
-
Notifications
You must be signed in to change notification settings - Fork 25
/
21_Translating_R_code.Rmd
722 lines (559 loc) · 14.5 KB
/
21_Translating_R_code.Rmd
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# Translating R code
**Learning objectives:**
- Build DSL (domain specific languages) to aid interoperability between R, HTML and LaTeX
- Reinforce metaprogramming concepts (expressions, quasiquotation, evaluation)
```{r, echo = FALSE, eval = TRUE}
DiagrammeR::mermaid("
graph LR
expressions --> R
quasiquotation --> R
evaluation --> R
R --> HTML
R --> LaTeX
")
```
<details>
<summary>Mermaid code</summary>
```{r, echo = TRUE, eval = FALSE}
DiagrammeR::mermaid("
graph LR
expressions --> R
quasiquotation --> R
evaluation --> R
R --> HTML
R --> LaTeX
")
```
</details>
<details>
<summary>Session Info</summary>
```{r, message = FALSE, warning = FALSE}
library(DiagrammeR) #for Mermaid flowchart
library(lobstr) #abstract syntax trees
library(purrr) #functional programming
library(rlang) #tidy evaluation
# from section 18.5
expr_type <- function(x) {
if (rlang::is_syntactic_literal(x)) {
"constant"
} else if (is.symbol(x)) {
"symbol"
} else if (is.call(x)) {
"call"
} else if (is.pairlist(x)) {
"pairlist"
} else {
typeof(x)
}
}
flat_map_chr <- function(.x, .f, ...) {
purrr::flatten_chr(purrr::map(.x, .f, ...))
}
switch_expr <- function(x, ...) {
switch(expr_type(x),
...,
stop("Don't know how to handle type ", typeof(x), call. = FALSE)
)
}
```
```{r}
utils::sessionInfo()
```
</details>
## Case Study: MCQ
We are going to use R code to generate HTML or LaTeX to produce multiple-choice questions such as
### Pop Quiz!
1. What is the **derivative** of $f(x) = 1 + 2\cos(3\pi x + 4)$?
a. $f'(x) = 6\pi\sin(3\pi x + 4)$
b. $f'(x) = -6\pi\sin(3\pi x + 4)$
c. $f'(x) = 24\pi\sin(3\pi x + 4)$
d. $f'(x) = -24\pi\sin(3\pi x + 4)$
![A whisker plot](images/translating/calculus_cat.png)
---
As developers, we may be asking ourselves:
* What are the expressions?
* What are the symbols?
* Will we have to quote inputs from the user (math teacher)?
## HTML
We are trying to produce
```{}
<body>
<h1 id = 'pop_quiz'>Pop Quiz</h1>
<ol>
<li>What is the <b>derivative</b> of $f(x) = 1 + 2\cos(3\pi x + 4)$?</li>
<ol>
<li>$f'(x) = 6\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = -6\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = 24\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = -24\pi\sin(3\pi x + 4)$</li>
</ol>
</ol>
<img src = 'calculus_cat.png' width = '100' height = '100' />
</body>
```
using DSL
```{r, eval = FALSE}
with_html(
body(
h1("Pop quiz!", id = "pop_quiz"),
ol(
li("What is the ", b("derivative"), "of $f(x) = 1 + 2cos(3pi x + 4)$?"),
ol(
li("$f'(x) = 6pi*sin(3pi x + 4)$"),
li("$f'(x) = -6pi*sin(3pi x + 4)$"),
li("$f'(x) = 24pi*sin(3pi x + 4)$"),
li("$f'(x) = -24pi*sin(3pi x + 4)$")
)
),
img(src = "images/translating/calculus_cat.png", width = 100, height = 100)
)
)
```
In particular,
* **tags** such as `<b></b>` have *attributes*
* **void tags** such as `<img />`
* special characters: `&`, `<`, and `>`
<details>
<summary>HTML verification</summary>
```{=html}
<body>
<h1 id = 'pop_quiz'>Pop Quiz</h1>
<ol>
<li>What is the <b>derivative</b> of $f(x) = 1 + 2\cos(3\pi x + 4)$?</li>
<ol>
<li>$f'(x) = 6\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = -6\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = 24\pi\sin(3\pi x + 4)$</li>
<li>$f'(x) = -24\pi\sin(3\pi x + 4)$</li>
</ol>
</ol>
<img src = 'images/translating/calculus_cat.png' width = '100' height = '100' />
</body>
```
</details>
## Escaping
* need to escape `&`, `<`, and `>`
* don't "double escape"
* leave HTML alone
### S3 Class
```{r}
html <- function(x) structure(x, class = "advr_html")
#dispatch
print.advr_html <- function(x, ...) {
out <- paste0("<HTML> ", x)
cat(paste(strwrap(out), collapse = "\n"), "\n", sep = "")
}
```
### Generic
```{r}
escape <- function(x) UseMethod("escape")
escape.character <- function(x) {
x <- gsub("&", "&", x)
x <- gsub("<", "<", x)
x <- gsub(">", ">", x)
html(x)
}
escape.advr_html <- function(x) x
```
### Checks
```{r}
escape("This is some text.")
escape("x > 1 & y < 2")
escape(escape("This is some text. 1 > 2")) #double escape
escape(html("<hr />")) #already html
```
## Named Components
```{}
li("What is the ", b("derivative"), "of $f(x) = 1 + 2\cos(3\pi x + 4)$?")
```
* aiming to classify `li` and `b` as **named components**
```{r}
dots_partition <- function(...) {
dots <- list2(...)
if (is.null(names(dots))) {
is_named <- rep(FALSE, length(dots))
} else {
is_named <- names(dots) != ""
}
list(
named = dots[is_named],
unnamed = dots[!is_named]
)
}
```
### Check
```{r}
str(dots_partition(company = "Posit",
software = "RStudio",
"DSLC",
"Cohort 9"))
```
<details>
<summary>HTML Attributes</summary>
Found among the textbook's [source code](https://github.com/hadley/adv-r/blob/master/dsl-html-attributes.r)
```{r}
html_attributes <- function(list) {
if (length(list) == 0) return("")
attr <- map2_chr(names(list), list, html_attribute)
paste0(" ", unlist(attr), collapse = "")
}
html_attribute <- function(name, value = NULL) {
if (length(value) == 0) return(name) # for attributes with no value
if (length(value) != 1) stop("`value` must be NULL or length 1")
if (is.logical(value)) {
# Convert T and F to true and false
value <- tolower(value)
} else {
value <- escape_attr(value)
}
paste0(name, "='", value, "'")
}
escape_attr <- function(x) {
x <- escape.character(x)
x <- gsub("\'", ''', x)
x <- gsub("\"", '"', x)
x <- gsub("\r", ' ', x)
x <- gsub("\n", ' ', x)
x
}
```
</details>
## Tags (calls)
```{r}
tag <- function(tag) {
new_function(
exprs(... = ), #arguments of new function
expr({ #body of the new function
#classify tags as named components
dots <- dots_partition(...)
#focus on named components as the tags
attribs <- html_attributes(dots$named)
# otherwise, nested code
children <- map_chr(dots$unnamed, escape)
# paste brackets, tag names, and attributes together
# then unquote user arguments
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env() #return the environment
)
}
```
<details>
<summary>Void tags</summary>
```{r}
void_tag <- function(tag) {
new_function(
exprs(... = ), #allows for missing arguments
expr({
dots <- dots_partition(...)
# error check
if (length(dots$unnamed) > 0) {
abort(!!paste0("<", tag, "> must not have unnamed arguments"))
}
attribs <- html_attributes(dots$named)
html(paste0(!!paste0("<", tag), attribs, " />"))
}),
caller_env()
)
}
```
</details>
### Checks
```{r}
tag("ol")
```
```{r}
img <- void_tag("img")
```
```{r, error = TRUE, results = "asis"}
img()
```
```{r}
img(src = "images/translating/calculus_cat.png",
width = 100,
height = 100)
```
## Tags (processing)
<details>
<summary>Venn Diagram</summary>
![Venn Diagram of words in R or HTML](images/translating/tags_r_venn.png)
```{r}
tags <- c("a", "abbr", "address", "article", "aside", "audio",
"b","bdi", "bdo", "blockquote", "body", "button", "canvas",
"caption","cite", "code", "colgroup", "data", "datalist",
"dd", "del","details", "dfn", "div", "dl", "dt", "em",
"eventsource","fieldset", "figcaption", "figure", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header",
"hgroup", "html", "i","iframe", "ins", "kbd", "label",
"legend", "li", "mark", "map","menu", "meter", "nav",
"noscript", "object", "ol", "optgroup", "option", "output",
"p", "pre", "progress", "q", "ruby", "rp","rt", "s", "samp",
"script", "section", "select", "small", "span", "strong",
"style", "sub", "summary", "sup", "table", "tbody", "td",
"textarea", "tfoot", "th", "thead", "time", "title", "tr",
"u", "ul", "var", "video"
)
void_tags <- c("area", "base", "br", "col", "command", "embed",
"hr", "img", "input", "keygen", "link", "meta", "param",
"source", "track", "wbr"
)
```
</details>
```{r}
html_tags <- c(
tags |> #list of tag names from HTML
set_names() |> #named variable to avoid reserved words!
map(tag), #make them function calls
void_tags |>
set_names() |>
map(void_tag)
)
```
### Example
```{r}
html_tags$ol(
html_tags$li("What is the ",
html_tags$b("derivative"),
"of $f(x) = 1 + 2cos(3pi x + 4)$?"))
```
## Bringing the HTML Together
```{r}
with_html <- function(code) {
eval_tidy(enquo(code), html_tags)
}
```
### Main Example
```{r}
with_html(
body(
h1("Pop quiz!", id = "pop_quiz"),
ol(
li("What is the ", b("derivative"), "of $f(x) = 1 + 2cos(3pi x + 4)$?"),
ol(
li("$f'(x) = 6pi*sin(3pi x + 4)$"),
li("$f'(x) = -6pi*sin(3pi x + 4)$"),
li("$f'(x) = 24pi*sin(3pi x + 4)$"),
li("$f'(x) = -24pi*sin(3pi x + 4)$")
)
),
img(src = "images/translating/calculus_cat.png", width = 100, height = 100)
)
)
```
### Check
```{=html}
<h1 id='pop_quiz'>Pop quiz!</h1><ol><li>What is the <b>derivative</b> of $f(x) = 1 + 2cos(3pi x + 4)$?</li><ol><li>$f'(x) = 6pi*sin(3pi x + 4)$</li><li>$f'(x) = -6pi*sin(3pi x + 4)$</li><li>$f'(x) = 24pi*sin(3pi x + 4)$</li><li>$f'(x) = -24pi*sin(3pi x + 4)$</li></ol></ol><img src='images/translating/calculus_cat.png' width='100' height='100' />
```
## LaTeX
```{r}
latex <- function(x) structure(x, class = "advr_latex")
print.advr_latex <- function(x) { cat("<LATEX> ", x, "\n", sep = "") }
```
### to_math
```{r, eval = FALSE}
to_math <- function(x) {
expr <- enexpr(x)
latex( #return LaTeX code
eval_bare( #eval_bare to ensure use of latex environment
expr, #expression (not quosure)
latex_env(expr) #need to define latex_env
))
}
```
## Known Symbols
```{r}
greek_letters <- c(
"alpha", "beta", "chi", "delta", "Delta", "epsilon", "eta",
"gamma", "Gamma", "iota", "kappa", "lambda", "Lambda", "mu",
"nu", "omega", "Omega", "phi", "Phi", "pi", "Pi", "psi", "Psi",
"rho", "sigma", "Sigma", "tau", "theta", "Theta", "upsilon",
"Upsilon", "varepsilon", "varphi", "varrho", "vartheta", "xi",
"Xi", "zeta"
)
greek_env <- rlang::as_environment(
rlang::set_names(
paste0("\\", greek_letters), #latex values
greek_letters #R names
)
)
```
```{r}
str(as.list(greek_env))
```
## Known Functions
### Unary Operations
```{r}
unary_op <- function(left, right) {
new_function(
exprs(e1 = ),
expr(
paste0(!!left, e1, !!right)
),
caller_env()
)
}
```
```{r}
#example
unary_op("\\sqrt{", "}")
```
### Binary Operations
```{r}
binary_op <- function(sep) {
new_function(
exprs(e1 = , e2 = ),
expr(
paste0(e1, !!sep, e2)
),
caller_env()
)
}
```
```{r}
#example
binary_op("+")
```
<details>
<summary>Even more LaTeX syntax</summary>
```{r}
known_func_env <- child_env(
.parent = empty_env(),
# Binary operators
`+` = binary_op(" + "),
`-` = binary_op(" - "),
`*` = binary_op(" * "),
`/` = binary_op(" / "),
`^` = binary_op("^"),
`[` = binary_op("_"),
# Grouping
`{` = unary_op("\\left{ ", " \\right}"),
`(` = unary_op("\\left( ", " \\right)"),
paste = paste,
# Other math functions
sqrt = unary_op("\\sqrt{", "}"),
sin = unary_op("\\sin(", ")"),
cos = unary_op("\\cos(", ")"),
tan = unary_op("\\tan(", ")"),
log = unary_op("\\log(", ")"),
abs = unary_op("\\left| ", "\\right| "),
frac = function(a, b) {
paste0("\\frac{", a, "}{", b, "}")
},
# Labelling
hat = unary_op("\\hat{", "}"),
tilde = unary_op("\\tilde{", "}")
)
```
</details>
## Unknown Symbols
```{r}
names_grabber <- function(x) {
switch_expr(x,
constant = character(),
symbol = as.character(x),
call = flat_map_chr(as.list(x[-1]), names_grabber)
) |>
unique()
}
```
$$x + y + f(a, b, c, 10)$$
```{r}
names_grabber(expr(x + y + f(a, b, c, 10)))
```
```{r}
lobstr::ast(expr(x + y + f(a, b, c, 10)))
```
## Unknown Functions
```{r}
calls_grabber <- function(x) {
switch_expr(x,
constant = ,
symbol = character(),
call = {
fname <- as.character(x[[1]])
children <- flat_map_chr(as.list(x[-1]), calls_grabber)
c(fname, children)
}
) |>
unique()
}
```
$$f(g + b, c, d(a))$$
```{r}
names_grabber(expr(f(g + b, c, d(a))))
calls_grabber(expr(f(g + b, c, d(a))))
lobstr::ast(expr(f(g + b, c, d(a))))
```
---
```{r}
seek_closure <- function(op) {
# change math font for function names
# apply ending parenthesis
new_function(
exprs(... = ),
expr({
contents <- paste(..., collapse = ", ")
paste0(!!paste0("\\mathrm{", op, "}("), contents, ")")
})
)
}
```
## Bringing the LaTeX Together
```{r}
latex_env <- function(expr) {
# Unknown Functions
calls <- calls_grabber(expr)
call_list <- map(set_names(calls), seek_closure)
call_env <- as_environment(call_list)
# Known Functions
known_func_env <- env_clone(known_func_env, call_env)
# Unknown Symbols
names <- names_grabber(expr)
symbol_env <- as_environment(set_names(names), parent = known_func_env)
# Known symbols
greek_env <- env_clone(greek_env, parent = symbol_env)
greek_env
}
to_math <- function(x) {
expr <- enexpr(x)
latex( #return LaTeX code
eval_bare( #eval_bare to ensure use of latex environment
expr, #expression (not quosure)
latex_env(expr) #need to define latex_env
))
}
```
### Check
```{r}
to_math(sin(pi) + f(a))
```
## Finishing the Example
(TO DO)
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/fixyitpXrwY")`
`r knitr::include_url("https://www.youtube.com/embed/h3RNPyhIjas")`
### Cohort 2
`r knitr::include_url("https://www.youtube.com/embed/pj0hTW1CtbI")`
### Cohort 3
(no video)
### Cohort 4
`r knitr::include_url("https://www.youtube.com/embed/0TclsXa085Y")`
### Cohort 5
`r knitr::include_url("https://www.youtube.com/embed/v_dkrIEdmKE")`
### Cohort 6
`r knitr::include_url("https://www.youtube.com/embed/_-uwFjO5CyM")`
<details>
<summary> Meeting chat log </summary>
```
00:30:16 Arthur Shaw: https://www.w3schools.com/html/html_entities.asp
00:32:29 Arthur Shaw: Beta symbol in HTML: Β
00:56:55 Arthur Shaw: https://dbplyr.tidyverse.org/articles/translation-function.html
00:57:48 Arthur Shaw: https://dtplyr.tidyverse.org/index.html
00:58:43 Arthur Shaw: https://dtplyr.tidyverse.org/articles/translation.html
```
</details>