Knitr Cheat Sheet



The simplest way to write a quick report, mixing in a bit of R, is to use R Markdown, a variant of Markdown developed by the folks at Rstudio. You should first read the page about Markdown. R Markdown is a variant of Markdown that has embedded R code chunks, to be used with knitr to make it easy to create reproducible web-based reports. The Markdown syntax has some enhancements. If you want to add R codes and outputs in your slides, use the Sweave (.Rnw) file so their colors will fit with the theme of the beamer. Otherwise you can use either the Sweave or TeX (.tex) file. For more information about knitrand options of R code chunks, see the R Markdown cheat sheet. Create Awesome HTML Table with knitr::kable and kableExtra. The key tool for R is knitr, which allows you to create a document that is a mixture of text and some chunks of code. When the document is processed by knitr, chunks of R code will be executed, and graphs or other results inserted. This sort of idea has been called “literate programming”. 10.1 The function knitr::kable The kable function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

  1. R Markdown Cheat Sheet Pdf
  2. Knitr Cheat Sheet 2020
  3. Knitr Cheat Sheet Download
  4. R Markdown Reference Guide
  5. Md File Cheat Sheet
  6. R Markdown Tutorial
  7. R Markdown Cheat Sheet

Overview

Questions
  • How can I integrate software and reports?

Objectives
  • Understand the value of writing reproducible reports

  • Learn how to recognise and compile the basic components of an R Markdown file

  • Become familiar with R code chunks, and understand their purpose, structure and options

  • Demonstrate the use of inline chunks for weaving R outputs into text blocks, for example when discussing the results of some calculations

  • Be aware of alternative output formats to which an R Markdown file can be exported

R Markdown Cheat Sheet Pdf

Data analysis reports

Data analysts tend to write a lot of reports, describing theiranalyses and results, for their collaborators or to document theirwork for future reference.

Many new users begin by first writing a single R script containing all of thework. Then simply share the analysis by emailing the script and various graphsas attachments. But this can be cumbersome, requiring a lengthy discussion toexplain which attachment was which result.

Writing formal reports with Word or LaTeXcan simplify this by incorporating both the analysis report and output graphs into a single document. But tweaking formatting to make figures look correctand fix obnoxious page breaks can be tedious and lead to a lengthly “whacka mole” game of fixing new mistakes resulting from a single formatting change.

Creating a web page (as an html file) by using R Markdown makes things easier.The report can be one long stream, so tall figures that wouldn’t ordinary fit onone page can be kept full size and easier to read, since the reader can simplykeep scrolling. Formatting is simple and easy to modify, allowing you to spendmore time on your analyses instead of writing reports.

Literate programming

Ideally, such analysis reports are reproducible documents: If anerror is discovered, or if some additional subjects are added to thedata, you can just re-compile the report and get the new or correctedresults (versus having to reconstruct figures, paste them intoa Word document, and further hand-edit various detailed results).

The key R package is knitr. It allows youto create a document that is a mixture of text and chunks ofcode. When the document is processed by knitr, chunks of code willbe executed, and graphs or other results inserted into the final document.

This sort of idea has been called “literate programming”.

knitr allows you to mix basically any sort of text with code from different programming languages, but we recommend that you use R Markdown, which mixes Markdownwith R. Markdown is a light-weight mark-up language for creating webpages.

Creating an R Markdown file

Within RStudio, click File → New File → R Markdown andyou’ll get a dialog box like this:

You can stick with the default (HTML output), but give it a title.

Basic components of R Markdown

The initial chunk of text (header) contains instructions for R to specify what kind of document will be created, and the options chosen. You can use the header to give your document a title, author, date, and tell it that you’re going to wantto produce html output (in other words, a web page).

You can delete any of those fields if you don’t want themincluded. The double-quotes aren’t strictly necessary in this case.They’re mostly needed if you want to include a colon in the title.

RStudio creates the document with some example text to get youstarted. Note below that there are chunks like

Knitr Cheat Sheet 2020

These are chunks of R code that will be executed by knitr and replacedby their results. More on this later.

Also note the web address that’s put between angle brackets (< >) aswell as the double-asterisks in **Knit**. This isMarkdown.

Markdown

Markdown is a system for writing web pages by marking up the text muchas you would in an email rather than writing html code. The marked-uptext gets converted to html, replacing the marks with the properhtml code.

For now, let’s delete all of the stuff that’s there and write a bit ofmarkdown.

You make things bold using two asterisks, like this: **bold**,and you make things italics by using underscores, like this:_italics_.

You can make a bulleted list by writing a list with hyphens orasterisks, like this:

Knitr

or like this:

Each will appear as:

  • bold with double-asterisks
  • italics with underscores
  • code-type font with backticks

You can use whatever method you prefer, but be consistent. This maintains thereadability of your code.

You can make a numbered list by just using numbers. You can even use thesame number over and over if you want:

This will appear as:

  1. bold with double-asterisks
  2. italics with underscores
  3. code-type font with backticks

You can make section headers of different sizes by initiating a linewith some number of # symbols:

You compile the R Markdown document to an html webpage by clickingthe “Knit” button in the upper-left.

Challenge 1

Create a new R Markdown document. Delete all of the R code chunksand write a bit of Markdown (some sections, some italicizedtext, and an itemized list).

Knitr

Convert the document to a webpage.

Solution to Challenge 1

In RStudio, select File > New file > R Markdown…

Delete the placeholder text and add the following:

Then click the ‘Knit’ button on the toolbar to generate an html document (webpage).

A bit more Markdown

You can make a hyperlink like this:[text to show](http://the-web-page.com).

You can include an image file like this: ![caption](http://url/for/file)

You can do subscripts (e.g., F~2~) with F~2~ and superscripts (e.g.,F^2^) with F^2^.

If you know how to write equations inLaTeX, you can use $ $ and $$ $$ to insert math equations, like$E = mc^2$ and

You can review Markdown syntax by navigating to the“Markdown Quick Reference” under the “Help” field in the toolbar at the top of RStudio.

R code chunks

The real power of Markdown comes frommixing markdown with chunks of code. This is R Markdown. Whenprocessed, the R code will be executed; if they produce figures, thefigures will be inserted in the final document.

The main code chunks look like this:

Markup language cheat sheet

That is, you place a chunk of R code between ```{r chunk_name}and ```. You should give each chunka unique name, as they will help you to fix errors and, if any graphs areproduced, the file names are based on the name of the code chunk thatproduced them.

Challenge 2

Add code chunks to:

  • Load the ggplot2 package
  • Read the gapminder data
  • Create a plot

Solution to Challenge 2

How things get compiled

When you press the “Knit” button, the R Markdown document isprocessed by knitr and a plain Markdowndocument is produced (as well as, potentially, a set of figure files): the R code is executedand replaced by both the input and the output; if figures areproduced, links to those figures are included.

The Markdown and figure documents are then processed by the toolpandoc, which converts the Markdown file into anhtml file, with the figures embedded.

Knitr Cheat Sheet Download

Chunk options

There are a variety of options to affect how the code chunks aretreated. Here are some examples:

  • Use echo=FALSE to avoid having the code itself shown.
  • Use results='hide' to avoid having any results printed.
  • Use eval=FALSE to have the code shown but not evaluated.
  • Use warning=FALSE and message=FALSE to hide any warnings ormessages produced.
  • Use fig.height and fig.width to control the size of the figuresproduced (in inches).

So you might write:

Often there will be particular options that you’ll want to userepeatedly; for this, you can set global chunk options, like so:

The fig.path option defines where the figures will be saved. The /here is really important; without it, the figures would be saved inthe standard place but just with names that begin with Figs.

If you have multiple R Markdown files in a common directory, you mightwant to use fig.path to define separate prefixes for the figure filenames, like fig.path='Figs/cleaning-' and fig.path='Figs/analysis-'.

Challenge 3

Use chunk options to control the size of a figure and to hide thecode.

Solution to Challenge 3

Knitr

You can review all of the R chunk options by navigating tothe “R Markdown Cheat Sheet” under the “Cheatsheets” section of the “Help” field in the toolbar at the top of RStudio.

Inline R code

You can make every number in your report reproducible. Use`r and ` for an in-line code chunk,like so: `r round(some_value, 2)`. The code will beexecuted and replaced with the value of the result.

Don’t let these in-line chunks get split across lines.

Perhaps precede the paragraph with a larger code chunk that doescalculations and defines variables, with include=FALSE for that largerchunk (which is the same as echo=FALSE and results='hide').

Rounding can produce differences in output in such situations. You may want2.0, but round(2.03, 1) will give just 2.

Themyroundfunction in the R/broman package handlesthis.

Challenge 4

Try out a bit of in-line R code.

Solution to Challenge 4

Here’s some inline code to determine that 2 + 2 = `r2+2`.

Other output options

You can also convert R Markdown to a PDF or a Word document. Click thelittle triangle next to the “Knit” button to get a drop-downmenu. Or you could put pdf_document or word_document in the initial headerof the file.

Tip: Creating PDF documents

R Markdown Reference Guide

Creating .pdf documents may require installation of some extra software. Ifrequired this is detailed in an error message.

  • TeX installers for Windows.
  • TeX installers for macOS.

Resources

Md File Cheat Sheet

  • Dynamic Documents with R and knitr (book)
  • R Markdown: The Definitive Guide (book by Rstudio team)

R Markdown Tutorial

Key Points

R Markdown Cheat Sheet

  • Mix reporting written in R Markdown with software written in R.

  • Specify chunk options to control formatting.

  • Use knitr to convert these documents into PDF and other formats.





Comments are closed.