-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFunWithRMarkdown.Rmd
437 lines (311 loc) · 11.1 KB
/
FunWithRMarkdown.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
---
title: "Fun with R Markdown"
author: "Brian A. Fannin"
date: "September 20, 2015"
output:
slidy_presentation:
self_contained: true
duration: 45
---
# Overview
- What can you do with R Markdown?
- Where did it come from?
- How does it work?
# What can I do?
- Write a book - http://adv-r.had.co.nz/
- Write a blog - [PirateGrunt.com](PirateGrunt.com)
- Create a website - http://rmarkdown.rstudio.com/
- Add a vignette to a package - http://yihui.name/knitr/demo/vignette/
- Publish research - https://github.com/rstudio/rticles
- Automate business intelligence
- Preserve your sanity
# How can I do this?
### Literate programming
Incorporate text (including markup) with computer instructions and the output from computer instructions.
> "The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style."
> - Donald Knuth
Within the R world, this began with Sweave.
- https://en.wikipedia.org/wiki/Literate_programming
- http://www.literateprogramming.com/knuthweb.pdf
# Sweave
- Incorporates or "weaves" R commands into a LateX document.
- Pretty old (first appeared in 2002)
- Only supports R as a programming language
- Only supports LateX for markup
- https://www.statistik.lmu.de/~leisch/Sweave/
- .Rnw -> R "noweb" http://www.cs.tufts.edu/~nr/noweb/
# Sweave - how does it work?
- Write a markup document, just as you always would
- Include R code in "chunks"
```
This is some LateX text.
\begin{RidiculousMarkup}
<<echo = FALSE, fig = TRUE>>=
# This is an R code chunk.
dfAwesomeData <- data.frame(x = someVariable, y = someOtherVariable)
plt <- ggplot(dfAwesomeData, aes(x = x, y = y)) + geom_line()
plt
@
And now we're back to LateX.
\end{AbsurdCommands}
```
# Demo
Example_Sweave.Rnw
Example_Beamer.Rnw
# Comments
- Sweave just produces TEX output. You still need an engine to render the final .PDF
- MikTeX (http://miktex.org/) works fine for me
- Probably sufficient if you're an academic
For most people (or at least Yihui Xie), Sweave wasn't enough. More output formats, more input languages, hooks, etc.
Enter knitr.
# knitr
- Same basic concept as Sweave
- Multi-language engine
- Multiple processing options
- knitr
- Rhtml-
- brew
- Others (Rrst, Rtex, Rasciidoc)
- http://yihui.name/knitr/
- cheat sheet - https://cran.r-project.org/web/packages/knitr/vignettes/knitr-refcard.pdf
# knitr
Code chunks look a little different.
- We must specify the language engine
- Code chunks may use R expressions, i.e. we may conditionally execute
<!-- https://ramnathv.github.io/posts/verbatim-chunks-knitr/ -->
```{r cache = F, echo = FALSE}
knitr::knit_hooks$set(source = function(x, options){
if (!is.null(options$verbatim) && options$verbatim){
opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
bef = sprintf('\n\n ```{r %s}\n', opts, "\n")
stringr::str_c(
bef,
knitr:::indent_block(paste(x, collapse = '\n'), " "),
"\n ```\n"
)
} else {
stringr::str_c("\n\n```", tolower(options$engine), "\n",
paste(x, collapse = '\n'), "\n```\n\n"
)
}
})
```
```{r echo = TRUE, verbatim = TRUE}
library(ggplot2)
data(movies)
m <- ggplot(movies, aes(x = rating)) + geom_density()
m
```
# Quick demo
Example_Markdown.Rmd
# knitr hooks
`knitr` supports user-defined pre- and post-processing of code chunks. In fact, I used one two slides ago, obtained from https://ramnathv.github.io/posts/verbatim-chunks-knitr/
```{r echo = TRUE, verbatim = TRUE, eval = FALSE}
knitr::knit_hooks$set(source = function(x, options){
if (!is.null(options$verbatim) && options$verbatim){
opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
bef = sprintf('\n\n ```{r %s}\n', opts, "\n")
stringr::str_c(
bef,
knitr:::indent_block(paste(x, collapse = '\n'), " "),
"\n ```\n"
)
} else {
stringr::str_c("\n\n```", tolower(options$engine), "\n",
paste(x, collapse = '\n'), "\n```\n\n"
)
}
})
```
http://yihui.name/knitr/hooks/
# knitr options
Very similar to a hook, you can set an upload function within the package options. This works fairly well with the `RWordpress` package.
```{r eval=FALSE, echo = TRUE, verbatin = TRUE}
opts_knit$set(upload.fun = WrapWordpressUpload, base.url = NULL)
WrapWordpressUpload = function(file) {
result = RWordpress::uploadFile(file)
result$url
}
options(WordPressLogin = c(PirateGrunt = "myPassword")
, WordPressURL = "http://PirateGrunt.wordpress.com/xmlrpc.php")
RWordpress::knit2wp("MyCoolPost.Rmd"
, title = "Catchy title"
, publish = FALSE
, shortcode = TRUE
, categories = c("R"))
```
RWordpress hasn't been updated in a while. Written by Duncan Temple Lang, so nice pedigree, but could be out of date.
http://yihui.name/knitr/demo/wordpress/
http://www.omegahat.org/RWordPress/
# knitr + Markdown = R markdown
- Unifies multiple output formats by having content written in markdown, rather than a specific markup language
- Once the markdown output is generated use `pandoc` to render in other markup languages
- Comes for free with RStudio
# Markdown
> "A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions." – John Gruber
- Very simple syntax
- Human readable
- May be converted into other formats
- Read about the life of Aaron Swartz
- http://daringfireball.net/projects/markdown/
# Pandoc
- Haskell tool written by John MacFarlane
- Recognizes that most markup languages have common features: level 1-n text, hyperlinks, tables, images
- MS Word uses XML -> that's another markup language!
http://pandoc.org/
---
First we mark down, then we mark up
Got it? Good.
> - Also, YAML.
# YAML
YAML = "**Y**AML **A**in't **M**arkup **L**anguage"
> "What It Is: YAML is a human friendly data serialization standard for all programming languages."
```
---
title: "Fun with R Markdown"
author: "Brian A. Fannin"
date: "September 20, 2015"
output:
slidy_presentation:
self_contained: false
duration: 45
---
```
Fun fact: JSON is a subset of YAML
http://yaml.org/
# R markdown from the command line
```
render(input, output_format = NULL, output_file = NULL, output_dir = NULL,
output_options = NULL, intermediates_dir = NULL,
runtime = c("auto", "static", "shiny"),
clean = TRUE, params = NULL, envir = parent.frame(),
quiet = FALSE, encoding = getOption("encoding"))
```
```
rmarkdown::render(myFile, output)
```
# HTML
- CSS
- Build your own website
- Nothing stopping you from using JavaScript libraries like Bootstrap and D3.
- If you're targeting HTML, you can use HTML within the R markdown document itself
- If you do, you'll need to write or copy a fair bit of HTML, css and java script
- Blog like a boss
# Basic site demo
# Other stuff
- Tables
- Customized reporting with `whisker`
- Jekyll
- Jupyter
- Creating your own templates
# Tables
- [xtable] (http://xtable.r-forge.r-project.org/)
- knitr::kable
- [pander] (http://rapporter.github.io/pander/)
- [DT] (https://rstudio.github.io/DT/)
# Table data
```{r }
data(Master, package = "Lahman")
Master <- head(Master[, 1:5], 5)
```
# xtable
```{r echo = TRUE, results = 'asis'}
library(xtable)
print(xtable(Master), type = 'html')
```
# kable
```{r echo=TRUE, results = 'asis'}
knitr::kable(Master)
```
# pander
```{r results = 'asis', echo=TRUE}
pander::pandoc.table(Master)
```
# DT
```{r }
DT::datatable(Master)
```
# Tables
Of these options, I tend to use `pander` most often.
- Possible to allow the table to break across pages
- Easy to control where breaks happen
- Easy to align columns
DT is super awesome for easy data search. Loads of bells and whistles on the package site: https://rstudio.github.io/DT/.
Note that this discussion of tables has _nothing_ to do with neat tabular output from functions like `lm`. For that, check out [`stargazer`](https://cran.r-project.org/web/packages/stargazer/index.html)
# `whisker` and moustache templates
- Uses the [`whisker`](https://github.com/edwindj/whisker) package
- Wrap merge fields in triple braces
- Pass merge values in with a named list
This is not the same thing as a "parameterized report" described here: http://rmarkdown.rstudio.com/developer_parameterized_reports.html
# Moustache example
<!--
Why am I not evaluating this code chunk? Because, rendering a markdown file from within a markdown file, causes an error:
'Error in env$metadata <- list() :
cannot change value of locked binding for 'metadata''
See this issue: https://github.com/rstudio/rmarkdown/issues/248
-->
```{r MoustacheExample, echo = TRUE, eval = FALSE}
library(whisker)
data <- list(Hitter1 = "Sammy Sosa"
, Hitter2 = "Pete Rose"
, NameId1 = "sosasa01"
, NameId2 = "rosepe01")
outFile <- whisker.render(readLines("Example_Whisker.Rmd"), data)
writeLines(outFile, "SosaVsRose.Rmd")
rmarkdown::render("SosaVsRose.Rmd", envir = new.env(), runtime = "static", quiet = TRUE)
```
# Jekyll
- http://jekyllrb.com/
- Converts markdown into static HTML
- Great for blogging and simple page design
- Default engine for GitHub pages
- Liquid templating system
- With effort, we can use moustache templating in R
- See also: StaticDocs - https://github.com/hadley/staticdocs
#
The rendering could probably be done in a makefile.
```
$ Rscript rmarkdown::render(inFile, markdown)
$ jekyll serve
```
# Jekyll demo
# Jupyter
- Saves the commands and output of an interactive session
- Formerly IPython
- Support for over 50 language kernels
- You'll need python
- Then get install instructions here: http://jupyter.readthedocs.org/en/latest/install.html
- And the R kernel http://irkernel.github.io/installation/ (They've clearly not heard of devtools)
>- I couldn't get it to work locally
# Customized templates
- Possible to roll your own template
- Pandoc template:
- Uses a templating framework wherein field delimited by `$` are replaced with YAML metadata, or command-line arguments
- http://pandoc.org/demo/example9/templates.html
- RStudio will recognize "skeletons" in the dialog box for a new RMarkdown document
- http://rmarkdown.rstudio.com/developer_document_templates.html
# Some cool pre-made templates
```{r eval=FALSE}
devtools::install_github("rstudio/rticles")
devtools::install_github("jjallaire/revealjs")
```
![alt text](images/NewRMarkdown.png)
# Customized template examples
- [JStatSoft](https://github.com/rstudio/rticles)
- [Tufte template](http://rmarkdown.rstudio.com/tufte_handout_format.html)
- [Reveal.js](https://github.com/jjallaire/revealjs)
# Stuff I didn't talk about
- Slidify
- http://slidify.org/
- Watch this space! Ramnath Vaidyanathan is pretty tremendous.
- Shiny Docs
- They're awesome, but require a big detour into Shiny, which is a talk unto itself.
>- Anybody want to create a Shiny talk?
# Two more references
- https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf
- https://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf
```{r eval=FALSE, echo=FALSE}
# Compost
# - Mathjax
# - Rd2HTML
```