forked from coatless-r-n-d/webR-quarto-demos
-
Notifications
You must be signed in to change notification settings - Fork 10
/
webr-quarto-html-demo.qmd
320 lines (261 loc) · 7.74 KB
/
webr-quarto-html-demo.qmd
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
---
title: "webR with Quarto HTML Standalone Document Proof of Concept"
subtitle: "Experiments with an Interactive Quarto Document using webR v0.1.0"
author: "James J Balamuta; modified by EEH"
engine: knitr
execute:
echo: true
error: true
embed-resources: true
format:
html:
toc: true
editor: source
---
# Demo
## Background
The purpose of this document is to explore how WebR can be embedded in a
Quarto Document for the purposes of teaching _R_.
- WebR Website: <https://docs.r-wasm.org/webr/latest/>
- WebR GitHub: <https://github.com/r-wasm/webr/>
## Setup
See the <https://github.com/coatless-r-n-d/webR-quarto-demos> for source.
```{=html}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css">
<style>
.CodeMirror pre {
background-color: unset !important;
}
.btn-webr {
background-color: #EEEEEE;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/r/r.js"></script>
<script type="module">
import { WebR } from "https://webr.r-wasm.org/v0.1.0/webr.mjs";
globalThis.webR = new WebR({
SW_URL: "/"
});
await globalThis.webR.init();
globalThis.webRCodeShelter = await new globalThis.webR.Shelter();
document.querySelectorAll(".btn-webr").forEach((btn) => {
btn.innerText = "Run code";
btn.disabled = false;
});
</script>
```
```{r}
#| results: asis
#| echo: false
webr_counter = 0
cat("importScripts('https://webr.r-wasm.org/v0.1.0/webr-worker.js');", file = "webr-worker.js")
cat("importScripts('https://webr.r-wasm.org/v0.1.0/webr-serviceworker.js');", file = "webr-serviceworker.js")
webr_editor = function(code = I(encodeString(code, quote = '`')), width, height) {
webr_counter <<- webr_counter + 1
output = glue::glue('
<button class="btn btn-default btn-webr" disabled type="button" id="webr-run-button-{{ webr_counter }}">Loading webR...</button>
<div id="webr-editor-{{ webr_counter }}"></div>
<div id="webr-code-output-{{ webr_counter }}"><pre style="visibility: hidden"></pre></div>
<script type="module">
const runButton = document.getElementById("webr-run-button-{{ webr_counter }}");
const outputDiv = document.getElementById("webr-code-output-{{ webr_counter }}");
const editorDiv = document.getElementById("webr-editor-{{ webr_counter }}");
const editor = CodeMirror((elt) => {
elt.style.border = "1px solid #eee";
elt.style.height = "auto";
editorDiv.append(elt);
},{
value: {{code}},
lineNumbers: true,
mode: "r",
theme: "light default",
viewportMargin: Infinity,
});
runButton.onclick = async () => {
runButton.disabled = true;
let canvas = undefined;
await globalThis.webR.init();
await webR.evalRVoid("canvas(width={{width}}, height={{height}})");
const result = await webRCodeShelter.captureR(editor.getValue(), {
withAutoprint: true,
captureStreams: true,
captureConditions: false,
env: webR.objs.emptyEnv,
});
try {
await webR.evalRVoid("dev.off()");
const out = result.output.filter(
evt => evt.type == "stdout" || evt.type == "stderr"
).map((evt) => evt.data).join("\\n");
const msgs = await webR.flush();
msgs.forEach(msg => {
if (msg.type === "canvasExec"){
if (!canvas) {
canvas = document.createElement("canvas");
canvas.setAttribute("width", 2 * {{width}});
canvas.setAttribute("height", 2 * {{height}});
canvas.style.width="700px";
canvas.style.display="block";
canvas.style.margin="auto";
}
Function(`this.getContext("2d").${msg.data}`).bind(canvas)();
}
});
outputDiv.innerHTML = "";
const pre = document.createElement("pre");
if (/\\S/.test(out)) {
const code = document.createElement("code");
code.innerText = out;
pre.appendChild(code);
} else {
pre.style.visibility = "hidden";
}
outputDiv.appendChild(pre);
if (canvas) {
const p = document.createElement("p");
p.appendChild(canvas);
outputDiv.appendChild(p);
}
} finally {
webRCodeShelter.purge();
runButton.disabled = false;
}
}
await globalThis.webR.init();
runButton.innerText = "Run code";
runButton.disabled = false;
</script>
', .open = "{{", .close = "}}")
}
```
```{r}
#| echo: false
knitr::knit_engines$set(webr = function(options) {
code = paste(options$code, collapse = "\n")
w = knitr::opts_current$get('fig.width') * 72
h = knitr::opts_current$get('fig.height') * 72
options$results = 'asis'
form = webr_editor(code = I(encodeString(code, quote = '`')), width = w, height = h)
form
}
)
```
## Exploration
Next, let's look at a few features of the language
### Linear Regression
We'll first start with the WebR team's demo example or the statistician way of
saying, "Hello world!"... Aka linear regression:
```{webr}
fit = lm(mpg ~ am, data=mtcars)
summary(fit)
```
### Retrieving prior objects
Each WebR cell appears to be connected to each other. Thus, we can access the
`fit` outcome:
```{webr}
coef(fit)
```
```{webr}
anova(fit)
```
### Mixing active and non-active _R_ code
For _if-else_ statements, we have:
```r
if (...) {
# Statements for TRUE
} else {
# Statements for FALSE
}
```
- `...` denotes a condition (either `TRUE` or `FALSE`)
- If `TRUE`, then run the statements inside `{}`
- Else, `FALSE`, carry on with your day.
How could we modify `temperature` to have the `if` statement print `"Hot!"`?
```{webr}
# Let's classify
temperature = 60
if (temperature > 76) {
print("Hot!")
} else {
print("Cold!")
}
```
### Summarize Data
Glancing at data frames yields:
```{webr}
summary(mtcars)
```
### Errors and Warnings
```{webr}
stop("What happens if an error is present?")
```
```{webr}
warning("You shouldn't be here...")
```
### Base graphics
Graphing with base R
```{webr}
plot(pressure)
```
More advanced base R graphing...
```{webr}
x1 = seq(0, 1, length = 20)
y1 = rep(0, 20)
x2 = rep(0, 20)
y2 = seq(0.75, 0, length = 20)
plot(0, type = "n",
axes = FALSE, ylab = "", xlab = "",
xlim = c(0, 1), ylim = c(0, 0.75), asp = 1,
main = "Straight Lines as a Curve")
segments(x1, y1, x2, y2)
box(col = "grey")
```
### ggplot2 Graphics
Next, we look at using `ggplot2` graphics. By default, the `ggplot2` package
is not available as it is _dependency_ heavy.
```{=html}
<details>
<summary>
Package installation for `ggplot2` given by `webr::install("ggplot2")`
</summary>
Downloading webR package: cli
Downloading webR package: glue
Downloading webR package: gtable
Downloading webR package: isoband
Downloading webR package: rlang
Downloading webR package: lifecycle
Downloading webR package: MASS
Downloading webR package: lattice
Downloading webR package: nlme
Downloading webR package: Matrix
Downloading webR package: mgcv
Downloading webR package: farver
Downloading webR package: labeling
Downloading webR package: colorspace
Downloading webR package: munsell
Downloading webR package: R6
Downloading webR package: RColorBrewer
Downloading webR package: viridisLite
Downloading webR package: scales
Downloading webR package: fansi
Downloading webR package: magrittr
Downloading webR package: utf8
Downloading webR package: vctrs
Downloading webR package: pillar
Downloading webR package: pkgconfig
Downloading webR package: tibble
Downloading webR package: withr
Downloading webR package: ggplot2
</details>
```
```{webr}
# Install non-base R packages
webr::install("ggplot2")
# Load non-base packages like normal
library("ggplot2")
p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot()
```