forked from STAT545-UBC/STAT545-UBC-original-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block007_first-use-rmarkdown.html
332 lines (287 loc) · 20.1 KB
/
block007_first-use-rmarkdown.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Test drive R Markdown</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="libs/navigation-1.1/tabsets.js"></script>
<link href="libs/highlightjs-1.1/default.css" rel="stylesheet" />
<script src="libs/highlightjs-1.1/highlight.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-68219208-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs && document.readyState && document.readyState === "complete") {
window.setTimeout(function() {
hljs.initHighlighting();
}, 0);
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="libs/local/main.css" type="text/css" />
<link rel="stylesheet" href="libs/local/nav.css" type="text/css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<header>
<div class="nav">
<a class="nav-logo" href="index.html">
<img src="static/img/stat545-logo-s.png" width="70px" height="70px"/>
</a>
<ul>
<li class="home"><a href="index.html">Home</a></li>
<li class="faq"><a href="faq.html">FAQ</a></li>
<li class="syllabus"><a href="syllabus.html">Syllabus</a></li>
<li class="topics"><a href="topics.html">Topics</a></li>
<li class="people"><a href="people.html">People</a></li>
</ul>
</div>
</header>
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Test drive R Markdown</h1>
</div>
<div id="TOC">
<ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#step-0-software-installation-and-configuration">Step 0: Software installation and configuration</a></li>
<li><a href="#step-1-get-ready-to-work">Step 1: Get ready to work</a></li>
<li><a href="#step-2-practice-with-rstudios-boilerplate-r-markdown-document">Step 2: Practice with RStudio’s boilerplate R Markdown document</a></li>
<li><a href="#step-3-take-control-of-the-output-format">Step 3: Take control of the output format</a></li>
<li><a href="#step-4-swap-out-the-guts-of-the-document">Step 4: Swap out the “guts” of the document</a></li>
<li><a href="#step-5-develop-your-report">Step 5: Develop your report</a></li>
<li><a href="#step-6-publish-your-report">Step 6: Publish your report</a><ul>
<li><a href="#html-on-github">HTML on GitHub</a></li>
</ul></li>
<li><a href="#troubleshooting">Troubleshooting</a></li>
</ul>
</div>
<div id="overview" class="section level3">
<h3>Overview</h3>
<p>This describes a hands-on activity where the goal is to author an R Markdown document and render it to HTML.</p>
<p>For people also using Git and GitHub, we discuss how to keep the intermediate Markdown file, the figures, and what to commit to Git and push to GitHub. If GitHub is the primary venue, we render directly to GitHub-flavored markdown and never create HTML.</p>
<p>Here is the official R Markdown documentation: <a href="http://rmarkdown.rstudio.com" class="uri">http://rmarkdown.rstudio.com</a></p>
</div>
<div id="step-0-software-installation-and-configuration" class="section level3">
<h3>Step 0: Software installation and configuration</h3>
<p>We assume the following</p>
<ul>
<li>You’ve already <a href="git01_git-install.html">installed Git</a> and (probably) <a href="git02_git-clients.html">a Git client</a>.</li>
<li>You’ve already <a href="cm001_course-intro-sw-install-account-signup.html#register-a-github-account">registered a free GitHub account</a>.</li>
<li>You’ve already <a href="block000_r-rstudio-install.html">installed R and RStudio</a>.</li>
<li>You’ve <a href="git07_git-github-rstudio.html">tested your installation and configuration of Git, GitHub, and RStudio</a></li>
<li><del>You’ve completed <a href="hw01_edit-README.html">Homework 01</a> or an equivalent exercise to truly test all of the above and to introduce you to Markdown.</del></li>
</ul>
</div>
<div id="step-1-get-ready-to-work" class="section level3">
<h3>Step 1: Get ready to work</h3>
<p>Launch RStudio, probably in the Project that corresponds to the repository where you are keeping all STAT 545 coursework. Make sure the workspace is clean and you’ve launched a fresh R process. Make sure the working directory is sensible.</p>
<p>Git people: we assume you are working inside a Git repo – probably one that is already set up to push/pull with a GitHub remote. That is <a href="git07_git-github-rstudio.html">covered elsewhere</a>.</p>
</div>
<div id="step-2-practice-with-rstudios-boilerplate-r-markdown-document" class="section level3">
<h3>Step 2: Practice with RStudio’s boilerplate R Markdown document</h3>
<p>I am modelling “walk before you run” here. It is best, especially for novices, to increase complexity in small increments. We will test our system’s ability to render the <a href="http://en.wikipedia.org/wiki/%22Hello,_world!%22_program">“hello world”</a> of R Markdown documents before we muddy the waters with our own, probably buggy, documents.</p>
<p>Do this: <em>File > New File > R Markdown …</em></p>
<ul>
<li>Give it an informative title. This will appear in the document but does not necessarily have anything to do with the file’s name. But the title and filename should be similar! The title is for human eyeballs, so it can contain spaces and punctuation. The filename is for humans and computers, so it should have similar words in it but no spaces and no punctuation.</li>
<li>Accept the default Author or edit if you wish.</li>
<li>Accept the default output format of HTML.</li>
<li>Click OK.</li>
</ul>
<p>Save this document to a reasonable filename and location. The filename should end in <code>.Rmd</code> or <code>.rmd</code>. I <strong>highly recommend</strong> saving in the top-level of the directory that is also also a Git repository for your coursework and that is also an RStudio project and that is also current working directory. Trust me on this.</p>
<p>Git people: this is a decent time to commit your new Rmd.</p>
<p>Click on “Knit HTML” or do <em>File > Knit Document</em>. RStudio should display a preview of the resulting HTML. Also look at the file browser (which should be pointed at the directory where you saved the <code>.Rmd</code> file). You should see the R Markdown document, i.e. <code>foo.Rmd</code> AND the resulting HTML <code>foo.html</code>.</p>
<p>Congratulations, you’ve just made your first reproducible report with R Markdown.</p>
<p>Git people: this is a decent time to commit your new HTML. One day you might reconsider whether you want HTML in your repo, but don’t worry about that now.</p>
</div>
<div id="step-3-take-control-of-the-output-format" class="section level3">
<h3>Step 3: Take control of the output format</h3>
<p>Do you really want HTML? Do you only want HTML? If so, you can skip this step!</p>
<p>The magical process that turns your R Markdown to HTML is like so: <code>foo.Rmd --> foo.md --> foo.html</code>. Note the intermediate markdown, <code>foo.md</code>. By default RStudio discards this, but you might want to hold on to that markdown.</p>
<p>Why? GitHub gives very special treatment to markdown files. They are rendered in an almost HTML-like way. This is great because it preserves all the charms of plain text but gives you a pseudo-webpage for free when you visit the file in the browser. In contrast, HTML is rendered as plain text on GitHub and you’ll have to take special measures to see it the way you want.</p>
<p>In many cases, you <em>only want the markdown</em>. In that case, we switch the output format to <code>github_document</code>. This means render will be <code>foo.Rmd --> foo.md</code>, where <code>foo.md</code> is GitHub-flavored markdown. If you still want the HTML <em>but also the intermediate markdown</em>, there’s a way to request that too.</p>
<p><strong>Output format</strong> is one of the many things we can control in the YAML frontmatter – the text at the top of your file between leading and trailing lines of <code>---</code>.</p>
<p>You can make some changes via the RStudio IDE: click on the “gear” in the top bar of the source editor, near the “Knit HTML” button. Select “Output options” and go to the Advanced tab and check “Keep markdown source file.” Your YAML should now look more like this:</p>
<pre class="yaml"><code> ---
title: "Something fascinating"
author: "Jenny Bryan"
date: "`r format(Sys.Date())`"
output:
html_document:
keep_md: true
--- </code></pre>
<p>You should have gained the line <code>keep_md: true</code>. You can also simply edit the file yourself to achieve this.</p>
<p>In fact this hand-edit is necessary if you want to keep only markdown and get GitHub-flavored markdown. In that case, make your YAML look like this:</p>
<pre class="yaml"><code> ---
title: "Something fascinating"
author: "Jenny Bryan"
date: "`r format(Sys.Date())`"
output: github_document
--- </code></pre>
<p>Save!</p>
<p>Git people: this is a decent time to commit your edited Rmd.</p>
<p>Render via “Knit HTML” button.</p>
<p>Now revisit the file browser. In addition to <code>foo.Rmd</code>, you should now see <code>foo.md</code>. If there are R chunks that make figures, the usage of markdown output formats will also cause those figure files to be left behind in a sensibly named sub-directory, <code>foo_files</code>.</p>
<p>If you commit and push <code>foo.md</code> and everything inside <code>foo_files</code>, then anyone with permission to view your GitHub repo can see a decent-looking version of your report.</p>
<p>If your output format is <code>html_document</code>, you should still see <code>foo.html</code>. If your output format is <code>github_document</code> and you see <code>foo.html</code>, that’s leftover from earlier experiments. Delete that. It will only confuse you later.</p>
<p>Git people: this is a decent time to commit current state of everything.</p>
</div>
<div id="step-4-swap-out-the-guts-of-the-document" class="section level3">
<h3>Step 4: Swap out the “guts” of the document</h3>
<p>Select everything but the YAML frontmatter and … delete it!</p>
<p>Write a single English sentence.</p>
<p>Insert an empty R chunk, via the “Chunk” menu in upper right of source editor or with corresponding keyboard shortcut.</p>
<pre><code>```{r}
## insert your brilliant WORKING code here
```</code></pre>
<p>Insert 1 to 3 lines of functioning code that begin the task at hand. “Walk through” and run those lines using the “Run” button or the corresponding keyboard shortcut. You MUST make sure your code actually works!</p>
<p>Satisfied? Save!</p>
<p>Now render the whole document via “Knit HTML.” Voilà!</p>
<p>Git people: this is a decent time to commit.</p>
</div>
<div id="step-5-develop-your-report" class="section level3">
<h3>Step 5: Develop your report</h3>
<p>In this incremental manner, develop your report. Add code to this chunk. Refine it. Add new chunks. Go crazy! But keep running the code “manually” to make sure it works.</p>
<p>If it doesn’t work with you babysitting it, I can guarantee you it will fail, in a more spectacular and cryptic way, when run at arms-length via “Knit HTML” or <code>rmarkdown::render()</code>.</p>
<p>Clean out your workspace and restart R and re-run everything periodically, if things get weird. There are lots of chunk menu items and keyboard shortcuts to accelerate this workflow. Render the whole document often to catch errors when they’re easy to pinpoint and fix. Save often and commit every time you reach a point that you’d like as a “fall back” position.</p>
<p>You’ll develop your own mojo soon, but this should give you your first successful R Markdown experience.</p>
<p>Git people: keep making periodic commits. It’s probably better to err on the side of “too often” instead of “too seldom” at this point.</p>
</div>
<div id="step-6-publish-your-report" class="section level3">
<h3>Step 6: Publish your report</h3>
<p>If you’ve been making HTML, you can put that up on the web somewhere, email to your collaborator, whatever.</p>
<p>No matter what, technically you can publish this report merely by pushing a rendered version to GitHub. However, certain practices make this effort at publishing more satisfying for your audience.</p>
<p>Here are two behaviors I find very frustrating:</p>
<ul>
<li>“Here is my code. Behold.” This is when someone only pushes their source, i.e. R Markdown or R code AND they want other people to look at their “product”. The implicit assumption is that target audience will download code and run it. Sometimes the potential payoff simply does not justify this effort.</li>
<li>“Here is my HTML. Behold.” This is when someone doesn’t bother to edit the default output format and accepts HTML only. What am I supposed to do with HTML on GitHub?</li>
</ul>
<p>Creating, commiting, and pushing markdown is a very functional, lighweight publishing strategy. Use <code>output: github_document</code> or <code>keep_md: true</code> if output is <code>html_document</code>. In both cases, it is critical to also commit and push everything inside <code>foo_files</code>. Now people can visit and consume your work like any other webpage.</p>
<p>This is (sort of) another example of keeping things machine- and human-readable, which is bliss. By making <code>foo.Rmd</code> available, others can see and run your <strong>actual code</strong>. By sharing <code>foo.md</code> and/or <code>foo.html</code>, others can casually browse your end product and decide if they even want to bother.</p>
<div id="html-on-github" class="section level4">
<h4>HTML on GitHub</h4>
<p>HTML files, such as <code>foo.html</code>, are not immediately useful on GitHub (though your local versions are easily viewable). Visit one and you’ll see the raw HTML. Yuck. But there are ways to get a preview: such as <a href="https://rawgit.com" class="uri">https://rawgit.com</a> or <a href="http://htmlpreview.github.io" class="uri">http://htmlpreview.github.io</a>. Expect some pain with HTML files inside private repos. When it becomes vital for the whole world to see proper HTML in its full glory, it’s time to use a more sophisticated web publishing strategy.</p>
<p>I have more <a href="bit006_github-browsability-wins.html">general ideas</a> about how to make a GitHub repo function as a website.</p>
</div>
</div>
<div id="troubleshooting" class="section level3">
<h3>Troubleshooting</h3>
<p><strong>Make sure RStudio and the <code>rmarkdown</code> package (and its dependencies) are up-to-date.</strong> In case of catastrophic failure to render R Markdown, consider that your software may be too old. R Markdown has been developing rapidly (written 2015-09), so you need a very current version of RStudio and <code>rmarkdown</code> to enjoy all the goodies we describe in this course.</p>
<p><strong>Get rid of your <code>.Rprofile</code></strong>, at least temporarily. I have found that a “mature” <code>.Rprofile</code> that has accumulated haphazardly over the years can cause trouble. Specifically, if you’ve got anything in there relating to <code>knitr</code>, <code>markdown</code>, <code>rmarkdown</code> and RStudio stuff, it may be preventing the installation or usage of the most recent goodies (see above). Comment the whole file out or rename it something else and relaunch or even re-install RStudio.</p>
<p><strong>Insert a chunk in your <code>.Rmd</code> document so that it renders even when there are errors.</strong> Some errors are easier to diagnose if you can execute specific R statements during rendering and leave more evidence behind for forensic examination. Put this chunk:</p>
<pre><code>```{r setup, include = FALSE, cache = FALSE}
knitr::opts_chunk$set(error = TRUE)
```</code></pre>
<p>near the top of your R Markdown document if you want to soldier on through errors, i.e. turn <code>foo.Rmd</code> into <code>foo.md</code> and/or <code>foo.html</code> no matter what. This is also helpful if you are writing a tutorial and want to demo code that throws an error. You might want to keep this as an <a href="https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets">RStudio snippet</a> for easy insertion.</p>
<p><strong>Tolerate errors in one specific chunk.</strong> If it’s undesirable to globally accept errors, you can still do this for a specific chunk like so:</p>
<pre><code>```{r wing-and-a-prayer, error = TRUE}
## your sketchy code goes here ;)
```</code></pre>
<p><strong>Check your working directory.</strong> It’s going to break your heart as you learn how often your mistakes are really mundane and basic. Ask me how I know. When things go wrong consider:</p>
<ul>
<li>What is the working directory?</li>
<li>Is that file I want to read/write actually where I think it is?</li>
</ul>
<p>Drop these commands into R chunks to check the above:</p>
<ul>
<li><code>getwd()</code> will display working directory at <strong>run time</strong>. If you monkeyed around with working directory with, e.g., the mouse, maybe it’s set to one place for your interactive development and another when “Knit HTML” takes over?</li>
<li><code>list.files()</code> will list the files in working directory. Is the file you want even there?</li>
</ul>
<p><strong>Don’t try to change working directory within an R Markdown document</strong>. <a href="https://github.com/yihui/knitr/blob/master/FAQ.md">Just don’t</a>. That is all.</p>
<p><strong>Don’t be in a hurry to create a complicated sub-directory structure.</strong> RStudio/<code>knitr</code>/<code>rmarkdown</code> (which bring you the “Knit HTML” button) are rather opinionated about the working directory being set to the <code>.Rmd</code> file’s location and about all files living together in one big happy directory. This can all be worked around. But not today.</p>
</div>
<div class="footer">
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC 3.0 Creative Commons License</a>.
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>