0% found this document useful (0 votes)
21 views14 pages

R Markdown Report Formatting Guide

This document serves as a guide for writing reports using R Markdown, covering basic formatting, embedding code, and mathematical expressions. It includes sections on paragraph breaks, headers, lists, and code chunk options, along with examples for inline code and LaTeX math. Additionally, it provides tips for setting defaults for all chunks and further reading resources.

Uploaded by

kekosioanna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views14 pages

R Markdown Report Formatting Guide

This document serves as a guide for writing reports using R Markdown, covering basic formatting, embedding code, and mathematical expressions. It includes sections on paragraph breaks, headers, lists, and code chunk options, along with examples for inline code and LaTeX math. Additionally, it provides tips for setting defaults for all chunks and further reading resources.

Uploaded by

kekosioanna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Write Report Using R Markdown

Pengqi Liu

Monday, Oct 21, 2024

Contents
Basic Formatting in R Markdown 1
Paragraph Breaks and Forced Line Breaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Italics, Boldface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Quotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Computer Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Bullet Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Title, Author, Date, Output Format, Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . 3

Embedding Code 3
Inline Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Code Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Chunk Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Math in R Markdown 8
Some LaTeX Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Further Reading 14

Basic Formatting in R Markdown

Paragraph Breaks and Forced Line Breaks


To insert a break between paragraphs, include a single completely blank line.
To force a line break, put two blank spaces
at the end of a line.

To insert a break between paragraphs, include a single completely blank line.

To force a line break, put *two* blank spaces


at the end of a line.

1
Headers

The character # at the beginning of a line means that the rest of the line is interpreted as a section header.
The number of #s at the beginning of the line indicates whether it is treated as a section, sub-section, sub-
sub-section, etc. of the document. For instance, Basic Formatting in R Markdown above is preceded by
a single #, but Headers at the start of this paragraph was preceded by ##. Do not interrupt these headers
by line-breaks. The maximum number of # to produce a header is 6.

Italics, Boldface

Text to be italicized goes inside a pair of asterisks.


Text to be boldfaced goes inside two pairs of asterisks.

Text to be *italicized* goes inside a pair of *asterisks*.


Text to be **boldfaced** goes inside two pairs of **asterisks**.

Quotations

Set-off quoted paragraphs are indicated by an initial >:


A friend once said:

It’s always better to give than to receive.

Computer Type

Text to be printed in a fixed-width font, without further interpretation, goes in paired left-single-quotes,
a.k.a. “back-ticks”, without line breaks in your typing. (Thus sqrt vs. sqrt.) This font is usually used when
you want to type R functions or commands as text output. If you want to display multiple lines like this,
start them with three back ticks in a row on a line by themselves, and end them the same way:

Text to be printed in a fixed-width font, without further interpretation,


goes in paired left-single-quotes, a.k.a. "back-ticks", without line breaks
in your typing. (Thus ‘sqrt‘ vs. sqrt.) This font is usually used when you want
to type R functions or commands as text output.

Bullet Lists

Unordered

• Item 1
• Item 2
– Item 2a
– Item 2b

2
Ordered lists

1. Item 1
2. Item 2
3. Item 3
• Item 3a
• Item 3b

Title, Author, Date, Output Format, Table of Contents

You can specify things like title, author and date in the header of your R Markdown file:

---
title: Week 2 Tutorial
author: Your name
date: Monday, Sep 13, 2021
---

You can also use the header to tell R Markdown whether you want it to render to HTML, PDF, or Word:

---
title: Week 2 Tutorial
author: Your name
date: Monday, Sep 13, 2021
output: pdf_document
---

Adding a table of contents:

---
title: Week 2 Tutorial
author: Your name
date: Monday, Sep 13, 2021
output:
html_document:
toc: true
pdf_document:
toc: true
---

Embedding Code
Embed a chunk of code:

head(cars)

## speed dist
## 1 4 2
## 2 4 10

3
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10

plot(cars$speed, cars$dist, xlab="Speed (mph)", ylab="Stopping distance (ft)")


100 120
Stopping distance (ft)

80
60
40
20
0

5 10 15 20 25

Speed (mph)

Inline Code

The mean of the numbers 2,3,4 is 3.


Notice that inline code does not display the commands run, just their output.

Code Options

The echo = FALSE parameter was added to the code chunk to prevent printing of the R source code, i.e.,
only the output is printed. ```{r, echo=FALSE}
The following setting runs the code, but includes neither the text of the code nor its output. ```{r,
include=FALSE}
The following setting prints the code in the document, but does not run it: ```{r, eval=FALSE}

Tables

The knitr package contains a very basic command, kable, which will format an array or data frame more
nicely for display:

library(knitr) # Only need this the first time


kable(coefficients(summary(lm(cars$dist~cars$speed))))

4
Estimate Std. Error t value Pr(>|t|)
(Intercept) -17.579095 6.7584402 -2.601058 0.0123188
cars$speed 3.932409 0.4155128 9.463990 0.0000000

Chunk Options

Chunk options are set in chunk headers. The chunk header must be written in one line, so do not break the
header line.

Chunk Label

Use ```{r, cars} or ```{r, label='cars'} to name a chunk called “cars”. The chunk label for each
chunk must be unique, otherwise the following errors will occur when rendering the outcome documents:

Error in parse_block(g[-1], g[1], [Link], markdown_mode) :


Duplicate chunk label ’cars’, which has been used for the chunk:
summary(cars)
Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block
Execution halted

The cache and plot filenames are based on chunk labels.


Avoid spaces, periods ., and underscores _ in chunk labels. Hyphens - are good options as separators.

Code Evaluation

• The setting ```{r, eval=FALSE} prints the code in the outcome document without running the chunk.
By default, eval=TRUE.
• By default, R Markdown will re-run all of your code every time you knit your document. However,
You can ask R Markdown to keep track of whether a chunk of code has changed, and only re-run it if
it has. This can be done by setting ```{r, cache=TRUE}
– In the case that you want to re-run an unchanged chunk of code which calls the results from some
modified chunks, you can set autodep=TRUE.
– There is another option set by [Link]. If it is specified as [Link]=FALSE, R
Markdown will not re-run the chunk if the only change is on comments.

Display in Output Document

• The echo=FALSE parameter was added to the code chunk to prevent printing of the R source code.
```{r, echo=FALSE}
• The following setting runs the code, but includes neither the text of the code nor its output. ```{r,
include=FALSE}
• warning/message: By default, warning=TRUE, which prints any warnings in the output document. By
setting warning=FALSE, you can see the warnings in the console, but they will not occur in the output
document. Similar for message=FALSE
• comment: This parameter controls the prefix before each line of the text output. By default, it is set
to be comment='##'. Set comment='' will remove the default ##.
• tidy: By default, tidy=FALSE. If set tidy=TRUE, the R source code will be formatted in a tidy way.

5
Plots

• [Link]: This parameter controls which plots to be displayed in the output document.
– Default is [Link] = 'high', which merges low-level changes (lines(), points(), abline())
into high-level plots.
– [Link] = 'none': No plots from this chunk occurs in the output file.
– [Link] = 'all': Displays all plots.
– [Link] = 'first': Only displays the first plot.
– [Link] = 'last': Only displays the last plot.

dmean <- mean(cars$dist)


smean <- mean(cars$speed)
plot(cars)
100 120
80
dist

60
40
20
0

5 10 15 20 25

speed

abline(lm(cars$dist~cars$speed), col="red")

6
100 120
80
dist

60
40
20
0

5 10 15 20 25

speed

abline(v=smean, h=dmean, lty=2)


100 120
80
dist

60
40
20
0

5 10 15 20 25

speed

• [Link]: The default is [Link]='asis', which puts the plots immediately after the code gener-
ating them; the option [Link]='hold' puts all the plots at the end of a code chunk; the option
[Link]='hide' generates plot files but hides them in the output document.
• [Link]/[Link]: These parameters take numeric values. By default, both are set to be 7
inches.
– [Link]=c(5, 7) makes the figure in 5-inch width and 7-inch height at the same time.

7
• [Link]: This controls the ratio of height/width. It takes numeric values. When [Link] is specified,
the [Link] is calculated by [Link]*[Link].
– If both [Link] and [Link] are specified, [Link] will be ignored with a warning.
• [Link]/[Link]: Control the width and height of the plot in the output document. They can
be [Link]='0.4\\linewidth', [Link]='3in', or [Link]='10cm'.
• [Link]: Horizontal alignment of figures in the output document. Possible settings are
[Link]='default', [Link]='left', [Link]='right', [Link]='center'.
• [Link]: Add a caption under the figure.

Setting Defaults for All Chunks

You can tell R to set some defaults to apply to all chunks where you don’t specifically over-ride them:

# Need the knitr package to set chunk options


library(knitr)

# Set knitr options for knitting code into the report:


opts_chunk$set(cache=TRUE, autodep=TRUE, [Link]=FALSE,
message=FALSE, warning=FALSE)

You may use include=FALSE option for the above chunk when you write a report. You can over-ride these
defaults by setting options for individual chunks.
Moreover, [Link] allows you to make a chunk inherit chunk options of the others. For example, if
you want to make a chunk that inherits the chunk options of two chunks labeled as chunk-a and chunk-b,
respectively, then, you can set [Link]=I(c('chunk-a', 'chunk-b')). You can over-ride the referenced
chunk options by setting options for individual chunks.

Math in R Markdown
Inline math is marked off with a pair of dollar signs ($), as π or eiπ .

Inline math is marked off with a pair of dollar


signs (‘$‘), as $\pi$ or $e^{i\pi}$.

Displayed formulas are marked off with $$ and $$, as in


Z ∞ √
x2
e− 2 dx = 2π
−∞

Displayed formulas are marked off with ‘$$‘ and ‘$$‘, as in


$$\int_{-\infty}^{\infty} \, e^{-\frac{x^2}{2}} \, dx = \sqrt{2\pi}$$

Some LaTeX Basics

Once your text has entered math mode, R Markdown converts your text into math to a different program,
called LaTeX (pronounced “la-tech”).

8
Subscripts and Superscripts

To indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character
ˆ.
If the subscript or superscript has just one character, there is no need to delimit with braces. However, if
there is more than one character, braces must be used.
The following examples illustrate:

$$X_i$$
$$X_{i}$$

Xi
Xi

Notice that in the above case, braces were not actually needed.
In this next example, however, failure to use braces creates an error, as LaTeX sets only the first character
as a subscript

$$X_{i,j}$$
$$X_i,j$$

Xi,j

Xi , j

Here is an expression that uses both subscripts and superscripts

$$X^2_{i,j}$$

2
Xi,j

Square Roots

We indicate a square root using the \sqrt operator.

$$\sqrt{b^2 - 4ac}$$

p
b2 − 4ac

Fractions

Displayed fractions are typeset using the \frac operator.

$$\frac{4z^3}{16}$$

4z 3
16

9
Summation Expressions

These are indicated with the \sum operator, followed by a subscript for the material appearing below the
summation sign, and a superscript for any material appearing above the summation sign.
Here is an example.

$$\sum_{i=1}^{n} X^3_i$$

n
X
Xi3
i=1

Product Expressions

Use \prod command for


Q

n! = \prod_{i=1}^{n}{i}

n
Y
n! = i
i=1

Integrals

Use \int for


R

\int_{-\infty}^{\infty} \, e^{-\frac{x^2}{2}} \, dx = \sqrt{2\pi}

Z ∞ √
x2
e− 2 dx = 2π
−∞

Self-Sizing Parentheses

In LaTeX, you can create parentheses, brackets, and braces which size themselves automatically to contain
large expressions. You do this using the \left and \right operators. Here is an example

$$\sum_{i=1}^{n}\left( \frac{X_i}{Y_i} \right)$$

n  
X Xi
i=1
Yi

Same idea for \left[ \right] and \left\{ \right\}. Notice that in order to print out {, we need to type
\{, that is, {}.

10
Greek Letters

Many statistical expressions use Greek letters. Much of the Greek alphabet is implemented in LaTeX, as
indicated in the LaTeX cheat sheet available at the course website. There are both upper and lower case
versions available for some letters.

$$\alpha, \beta, \gamma, \Gamma$$

α, β, γ, Γ

Special Symbols

All common mathematical symbols are implemented, and you can find a listing on the LaTeX cheat sheet.
Some examples. (Notice that, in the third example, I use the tilde character for a forced space. Generally
LaTeX does spacing for you automatically, and unless you use the tilde character, R will ignore your attempts
to add spaces.)

$$a \pm b$$


$$x \ge 15$$
$$a_i \ge 0~~~\forall i$$

a±b
x ≥ 15
ai ≥ 0 ∀i

Special Functions

LaTeX typesets special functions in a different font from mathematical variables. These functions, such as
log, sin, cos, etc. are indicated in LaTeX with a backslash. Here is an example that also illustrates how to
typeset an integral.

$$\int_0^{2\pi} \sin x~dx$$

Z 2π
sin x dx
0

Matrices

Matrics are presented in the array environment. One begins with the statement \begin{array} and ends
with the statement \end{array}. Following the opening statement, a format code is used to indicate the
formatting of each column. In the example below, we use the code {rrr} to indicate that each column is
right justified. Each row is then entered, with cells separated by the & symbol, and each line (except the
last) terminated by \\.

11
$$\begin{array}
{rrr}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{array}
$$

1 2 3
4 5 6
7 8 9

In math textbooks, matrices are often surrounded by brackets, and are assigned to a boldface letter. Here
is an example

$$\mathbf{X} = \left[\begin{array}
{rrr}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{array}\right]
$$

 
1 2 3
X= 4 5 6 
7 8 9

Notice that the command \mathbf makes letters boldface. For outline font (“blackboard bold”), use \mathbb
command. For example, R.

Accents

\vec{a} produces ⃗a, \hat{a} produces â. Some accents, particularly hats, work better if they space out, as
with \widehat{\mathrm{Var}(Y)} producing Var(Y\).

Aligning Equations in your Solutions

Suppose you are asked to prove something that requires several lines of development. For example, suppose
you are proving that the sum of deviation scores is always equal to zero in any list of numbers. You can
align the equations by using \begin{aligned} \end{aligned} command1 .
Notice how I define new symbols \Xbar and \sumn to make things much simpler! Notice the key role
that the alignment tab character & plays in telling LaTeX where to align the equations. Also notice the
double-backslash newline character at the end of every line of the equation except the last.

$$
% Comment -- define some macros
\def\Xbar{\overline{X}_\bullet}
1 If you want to generate a PDF document, avoid using \begin{align} \end{align} and \begin{eqnarray} \end{eqnarray}.

For generating HTML, all of aligned, align, and eqnarray can be used for alignment.

12
\def\sumn{\sum_{i=1}^{n}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{aligned}
\sumn \left(X_i - \Xbar\right) &= \sumn X_i - \sumn \Xbar \\
&= \sumn X_i - n \Xbar \\
&= \sumn X_i - \sumn X_i \\
&= 0
\end{aligned}
$$

n
X n n
 X X
Xi − X • = Xi − X•
i=1 i=1 i=1
n
X
= Xi − nX •
i=1
Xn n
X
= Xi − Xi
i=1 i=1
=0

Aligning Equations with Comments

In proving a result, it is often useful to include comments. Here is an example of one way you can do that.

$$
\begin{aligned}
3+x &=4 && \text{(Solve for} x \text{.)}\\
x &=4-3 && \text{(Subtract 3 from both sides.)}\\
x &=1 && \text{(Yielding the solution.)}
\end{aligned}
$$

3+x=4 (Solve for x.)


x=4−3 (Subtract 3 from both sides.)
x=1 (Yielding the solution.)

New Commands

We can define new LaTeX command by using \newcommand. The text below creates a new LaTeX command
that defines \mx to be the equivalent of \mathbf.

\newcommand{\mx}[1]{\mathbf{#1}}

Once you’ve done this, you can use your new command. For example,

$$\mx{y} = \mx{X\beta}$$

13
yields
y = Xβ

Use \boldsymbol to make Greek letters bold:

y = Xβ

Further Reading
For a comprehensive reference of R Markdown, see R Markdown.
For a list of LaTeX mathematical symbols, see LaTeX Math Symbols.
For more chunk options, see Chunk Options.

14

You might also like